/**
 * 小票模型
 * @author jhua.zuo<jhua.zuo@baisonmail.com>
 * @date 2015-10-28
 */

angular.module('baisonReceipt', ['baisonDb', 'baisonService'])
        //小票表模型
        .factory('ReceiptRecord', ['$rootScope', '$q', 'apiService', 'timeStamp2String', 'dbReplace', 'dbInsertMulti', 'dbUpdate', 'dbSelect', 'dbGetOne', 'dbUpdateAdd', 'dbDelete', 'ruKu', 'BaseGoods','checkGetList','VIP', function ($rootScope, $q, apiService, timeStamp2String, dbReplace, dbInsertMulti, dbUpdate, dbSelect, dbGetOne, dbUpdateAdd, dbDelete, ruKu, BaseGoods,checkGetList,VIP) {
//              var shop_code = $rootScope.current_shop.ShopCode;
//              var user_code = $rootScope.user.UserCode;
//              var user_name = $rootScope.user.UserName;
                //查询一张小票 -------------------------------------------------
                var get_one = function (record_code) {
                    var filter = {'record_code': record_code};
                    return apiService('pos/pos/get_detail', filter);
                };

                var get_one_local = function (record_code) {
                    //从本地数据库获取小票的详细信息：主表/商品明细/支付/促销
                    var sql1 = 'select * from PosReceiptRecord where record_code="' + record_code + '"';
                    var sql2 = 'select * from PosReceiptDetail where record_code="' + record_code + '"';
                    var sql3 = 'select * from PosReceiptSettlement where record_code="' + record_code + '"';
                    var sql4 = 'select * from PosReceiptPromotion where record_code="' + record_code + '"';
                    return $q.all({
                        'record': dbSelect('YsPos', sql1),
                        'record_detail': dbSelect('YsPos', sql2),
                        'payment': dbSelect('YsPos', sql3),
                        'promotion': dbSelect('YsPos', sql4)
                    });
                };
                //查询一组小票 一天的 -------------------------------------------
                var get_day = function (filter, type) {
                    if (filter.vip_code == '' || filter.vip_code == undefined) {
                        filter.shop_code = $rootScope.current_shop.ShopCode;
                    }
                    if (type == 'main') {
                        filter.is_checkout = 1;
                        filter.is_return = 0;
                        filter.return_num = 1;
                    }
                    if (type == 'return') {
                        filter.is_checkout = 1;
                        filter.is_return = 1;
                    }
                    if (type == 'uncheck') {
                        filter.is_checkout = 0;
                    }
                    if (type == 'returnable') {
                        //todo 可退的小票条件
                        filter.is_checkout = 1;
                        filter.is_return = 0;
                        filter.return_num = 0;
                        filter.is_available_return = 1;

                    }
                    filter.is_cancel = 0;
                    return apiService('pos/pos/search_group_data', filter);
                };

                //获取所有本地已支付未上传,（需要上传）
                var get_list_local_not_upload = function () {
                    sql = 'select * from PosReceiptRecord where is_upload = "0" and is_checkout = "1" ' + 'order by record_time desc';
                    return dbSelect('YsPos', sql);
                };
                //获取本地当日支付
                var get_list_local = function (filter) {
                    sql = 'select * from PosReceiptRecord where record_time like "' + filter + '%" and is_checkout = "1" ';
                    return dbSelect('YsPos', sql);
                };
				
				//获取本地当日退款信息
				var get_return_list_local = function(filter){
					//var sql = 'select * from PosReceiptRecord where record_time like "' + filter + '%" and is_checkout = "1" and record_code like"' + 'LT' + '%"';
					var sql = 'select * from PosReceiptRecord where record_time like "' + filter + '%" and is_checkout = "1" and record_code like"' + 'LT' + '%"';
					
					return dbSelect('YsPos', sql);
				};

                //获取一天离线
                var get_list_local_offline = function (filter) {
                    var where = " 1=1 ";
                    if (typeof filter.record_time_start !== 'undefined') {
                        where = where + ' and record_time > "' + filter.record_time_start + '" ';
                    }
                    if (typeof filter.record_time_end !== 'undefined') {
                        where = where + ' and record_time < "' + filter.record_time_end + '" ';
                    }
                    if (filter.record_code) {
                        where = where + ' and record_code like "%' + filter.record_code + '" ';
                    }
                    //是否取前一天的数据
                    if (filter.is_pre == 1) {
                        var pre_sql = ' select max(record_time) record_time from PosReceiptRecord where record_time < ' + '"' + filter.day + '"' + ' limit 1 ';
                        return dbGetOne(pre_sql).then(function (ret) {
                            //console.log(ret);
                            if (ret.record_time == '' || ret.record_time == undefined) {
                                var deferred = $q.defer();
                                var promise = deferred.promise;
                                deferred.resolve('');
                                return promise;
                            } else {
                                filter.day = timeStamp2String(ret.record_time, 'date');
                                where = where + ' and record_time like "' + filter.day + '%" ' + 'order by record_time desc';
                                sql = 'select * from PosReceiptRecord where ' + where;
                                return dbSelect('YsPos', sql);
                            }
                        });
                    } else {
                        if (filter.day) {
                            where = where + ' and record_time like "' + filter.day + '%" ' + 'order by record_time desc';
                        }
                        sql = 'select * from PosReceiptRecord where ' + where;
                        return dbSelect('YsPos', sql);
                    }
                };

                //查询一组小票 多天的 -------------------------------------------
                var get_list = function (filter, type) {
                    var param = filter;
                    if (param.vip_code == '' || param.vip_code == undefined) {
                        param.shop_code = $rootScope.current_shop.ShopCode;
                    }
                    if (type == 'main') {
                        //普通小票
                        param.is_checkout = 1;
                        param.is_return = 0;
                        param.return_num = 1;
                    }
                    if (type == 'return') {
                        //退票
                        param.is_checkout = 1;
                        param.is_return = 1;
                    }
                    if (type == 'uncheck') {
                        //未支付的小票
                        param.is_checkout = 0;
                    }
                    if (type == 'returnable') {
                        //todo 可退的小票条件
                        param.is_checkout = 1;
                        param.is_return = 0;
                        param.return_num = 0;
                    }
                    filter.is_cancel = 0;
                    if (typeof filter.record_time_start !== 'undefined' && typeof filter.record_time_start !== 'string') {
                        param.record_time_start = timeStamp2String(filter.record_time_start, 'date');
                    }
                    if (typeof filter.record_time_end !== 'undefined' && typeof filter.record_time_end !== 'string') {
                        param.record_time_end = timeStamp2String(filter.record_time_end, 'date');
                    }
                    return apiService('pos/pos/search_group_data_by_cond', param);
                };
                
                //新增一张小票 -------------------------------------------------
                var add = function (data) {
                    //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg:data,title:'add'});
                    //如果没有单据编号则创建 规则为 店铺代码+毫秒时间戳
                    //if (typeof data.record_code === "undefined" || data.record_code == '') {
                    //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg:'here'});
                    //data.record_code = String(shop_code) + String(new Date().getTime());
                    //零售单据规则改为 前缀 + 年月日时分秒 + 2位随机位
                    data.record_code = 'LS' + timeStamp2String(0, 'datetime2') + (Math.random() * 9).toFixed(0) + (Math.random() * 9).toFixed(0);
                    $rootScope.goods_cart.record_code = data.record_code;
                    //}
                    //第一次创建增加制单日期
                    if (typeof data.record_time === "undefined" || data.record_time == '') {
                        data.record_time = timeStamp2String(0, 'datetime');
                    }
                    return add_local(data).then(function (success) {
                        return add_remote(data);
                    });
                };

                //新增一张小票到本地 --------------------------------------------
                var add_local = function (data) {
                    
                    var guide_user_name = '';
                    var guide_user_code = '';
                    data.list.forEach(function (ret) {
                        
                        var daogou_name = '';
                        data.guidelist.filter(function (guide) {
                            if (guide.UserCode == ret.daogou) {
                                daogou_name = guide.UserName;
                            }
                        });
                        
                        if (guide_user_name.length == 0) {
                            if (ret.daogou == $rootScope.user.UserCode) {
                                guide_user_name = $rootScope.user.UserName;
                                guide_user_code = $rootScope.user.UserCode;
                            } else {
                                guide_user_name = daogou_name;
                                guide_user_code = ret.daogou;
                            }
                        } else {
                            if (ret.daogou == $rootScope.user.UserCode) {
                                guide_user_name = ',' + $rootScope.user.UserName;
                                guide_user_code = ',' + $rootScope.user.UserCode;
                            } else {
                                guide_user_name = guide_user_name + ',' + daogou_name;
                                guide_user_code = guide_user_code + ',' + ret.daogou;

                            }

                        }
                    })

                    //组装本地保存数据_主表
                    var insert_data = {
                        'record_code': data['record_code'],
                        'record_time': data['record_time'],
                        'cashNum': $rootScope.cashNum, //收银台号
                        'cashDate': $rootScope.cashDate, //营业日期
                        //'cashStore':$rootScope.cashStore,  //库位
                        'shop_code': $rootScope.current_shop.ShopCode,
                        'trade_user_code': $rootScope.user.UserCode,
                        'trade_user_name': $rootScope.user.UserName,
                        'guide_user_name': guide_user_name,
                        'guide_user_code': guide_user_code,
                        'customer_code': data['vip']['customer_code'] ? data['vip']['customer_code'] : (data['vip']['customer_sn'] ? data['vip']['customer_sn'] : ''), //顾客代码
                        'vip_code': data['vip']['vip_code'] ? data['vip']['vip_code'] : '',
                        'num': data.info.total_num, //销售总数量 
                        'return_num': data.info.total_num,
                        'money': data.info.total_money, //销售总金额
                        'init_code': data['init_code'] ? data['init_code'] : '',
                        'pay_money': 0.00,
                        'change_money': 0.00,
                        'integral': 0,
                        'is_return': data['is_return'] ? data['is_return'] : 0,
                        'is_checkout': 0,
                        'is_checkout_time': '',
                        'remark': data['remark'] ? data['remark'] : '',
                        'cut_money': data.info.cut_money,
                        'final_money': data.info.total_money - data.info.discount_money, //最终支付金额
                        'lastchanged': timeStamp2String(0, 'datetime'),
                        'is_upload': 0,
                        'is_pending': data['is_pending'] ? data['is_pending'] : 0,
                        'discount_money': data.info.discount_money, //优惠总金额
                        'deviceId': baison_app.api.deviceId.toString()
                    };

                    //商品明细
                    var insert_details = [];
                    $.each(data.list, function (index, sku) {
                        var daogou_name = '';
                        data.guidelist.filter(function (guide) {
                            if (guide.UserCode == sku.daogou) {
                                daogou_name = guide.UserName;
                            }
                        });
                        insert_details.push({
                            'record_code': data.record_code,
                            'detail_index': sku.index,
                            'sku': sku.SkuCode,
                            'goods_name': sku.GoodsName,
                            'goods_code': sku.GoodsCode,
                            'property_name': sku.SkuPropertyName,
                            'daogou_code': sku.daogou,
                            'daogou_name': daogou_name,
                            'num': sku.num,
                            'money': sku.money,
                            'refer_price': sku.SkuPrice,
                            'price': sku.BuyPrice,
                            'rebate': sku.rebate,
                            'is_return': 0,
                            'return_num': 0,
                            'remark': '',
                            'final_money': 0,
                            'goods_status': sku.goods_status ? sku.goods_status : 0,
                            'color_code': sku.ColorCode,
                            'color_name': sku.ColorName,
                            'size_code': sku.SizeCode,
                            'size_name': sku.SizeName,
                            'integral_rate': '', //积分倍率
                            'birthday_offers': '', //生日优惠
                            'whole_pro': sku.whole_pro, //整单promotionid
                            'bind_pro': sku.bind_pro//捆绑promotionid
                        });
                    });

//                    baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg: insert_details});

                    //促销明细
                    var insert_proDetails = [];
                    if (data['current_promotions'].length !== 0) {
                        $.each(data['current_promotions'], function (i, n) {
                            var ProDetail = {
                                'record_code': data.record_code, //小票单号
                                'pro_record_code': n.record_code, //促销活动单号
                                'short_name': n.short_name, //促销活动简称
                                'promotion_type': n.promotion_type, //促销活动类型
                                'rebate': n.rebate, //促销折扣
                                'reduce_price': n.reduce_price, //促销减金额
                                'gift_total_price': n.gift_total_price,
                                'gift_total_num': n.gift_total_num,
                                'favorable_money': n.favorable_money
                            };
                            insert_proDetails.push(ProDetail);
                            //dbReplace('PosReceiptPromotion', [ProDetail], ['record_code'],['pro_record_code','short_name','promotion_type','rebate','reduce_price','gift_total_price','gift_total_num']);
                        });
                    }

                    //插入主表
                    return dbReplace('PosReceiptRecord', [insert_data], ['record_code'], ['record_code', 'record_time', 'shop_code', 'trade_user_code', 'customer_code', 'vip_code', 'num', 'money', 'init_code', 'pay_money', 'change_money', 'integral', 'is_checkout', 'is_checkout_time', 'remark', 'cut_money', 'final_money', 'lastchanged', 'is_upload', 'trade_user_name', 'guide_user_name', 'guide_user_code', 'is_pending'])
                            .then(function (success) {  //detail_index
                                //插入商品明细数据
                                return dbReplace('PosReceiptDetail', insert_details, ['detail_index'], ['record_code', 'detail_index', 'sku', 'goods_code', 'goods_name', 'property_name', 'daogou_code', 'daogou_name', 'num', 'money', 'refer_price', 'price', 'rebate', 'is_return', 'return_num', 'remark', 'final_money', 'goods_status', 'size_name', 'size_code', 'color_name', 'color_code', 'whole_pro', 'bind_pro']);
                            })
                            .then(function (success) {
                                //插入促销明细数据
                                return dbReplace('PosReceiptPromotion', insert_proDetails, ['record_code'], ['pro_record_code', 'short_name', 'promotion_type', 'rebate', 'reduce_price', 'gift_total_price', 'gift_total_num']);
                            });
                };

                //新增一张小票到服务器 ------------------------------------------
                var add_remote = function (data) {
                    //api.alert({msg:data,title:'add_remote'});
                    //组装服务器保存数据
                    //促销明细
                    var ProDetail = [];
                    if (Object.keys(data['current_promotions']).length !== 0) {
                        $.each(data['current_promotions'], function (i, n) {
                            ProDetail.push({
                                'record_code': data.record_code,
                                'pro_record_code': n.record_code,
                                'short_name': n.short_name,
                                'promotion_type': n.promotion_type,
                                'rebate': n.rebate,
                                'reduce_price': n.reduce_price,
                                'gift_total_price': n.gift_total_price,
                                'gift_total_num': n.gift_total_num,
                                'favorable_money': n.favorable_money
                            });
                        });
                    }

                    //主单信息
                    var record = {};
                    record.record_code = data.record_code;
                    record.cashNum = $rootScope.cashNum;
                    record.cashDate = $rootScope.cashDate;
                    record.cashStore = $rootScope.cashStore;
                    record.record_time = data.record_time;
                    record.vip_code = data.vip.vip_code;
                    record.customer_code = data['vip']['customer_code'] ? data['vip']['customer_code'] : (data['vip']['customer_sn'] ? data['vip']['customer_sn'] : ''), //顾客代码
                    record.is_return = data.is_return;
                    record.trade_user_code = $rootScope.user.UserCode;
                    record.shop_code = $rootScope.current_shop.ShopCode;
                    record.num = data.info.total_num;
                    record.return_num = data.info.total_num;
                    record.money = data.info.total_money;//data.info.daifu_money + data.info.discount_money;
                    //record.refer_money =  data.info.total_money;
                    record.init_code = data.init_code;
                    record.pay_money = 0;
                    record.change_money = 0;
                    record.integral = 0;
                    record.is_return = data.is_return;
                    record.is_checkout = 0;
                    record.is_checkout_time = '';
                    record.cut_money = data.info.cut_money;

                    record.discount_money = data.info.discount_money;//discount_money不包含抹零cut_money
                    record.final_money = data.info.total_money - data.info.discount_money;
                    record.lastchanged = timeStamp2String(0, 'datetime');
                    record.sell_time = data.record_time;
                    record.is_add_person = $rootScope.user.UserCode;
                    record.is_pending = data['is_pending'] ? data['is_pending'] : 0;
                    record.remark = data['remark'] ? data['remark'] : '';
                    record.allremark = data['allremark'] ? data['allremark'] : '';
                    record.deviceId = baison_app.api.deviceId.toString();
                    //商品明细
                    var details = [];
                    $.each(data.list, function (index, sku) {
                        /*
                        var daogou_name = '';
                        data.guidelist.filter(function (guide) {
                            if (guide.UserCode == sku.daogou) {
                                daogou_name = guide.UserName;
                            }
                        });
                        */
                        details.push({
                            'record_code': data.record_code,
                            'detail_index': sku.index,
                            'sku': sku.SkuCode,
                            //'property_name':sku.SkuPropertyName,
                            'goods_code': sku.GoodsCode,
                            'color_code': sku.ColorCode,
                            'size_code': sku.SizeCode,
                            //'daogou_code': (typeof sku.daogou == 'object') ?sku.daogou.UserCode:$rootScope.user.UserCode,
                            //'daogou_name':(typeof sku.daogou == 'object') ?sku.daogou.UserName:$rootScope.user.UserName,
                            'guide_user_code': sku.daogou,
                            'num': sku.num,
                            'money': sku.money,
                            'refer_price': sku.SkuPrice,
                            'price': sku.BuyPrice,
                            'rebate': sku.rebate,
                            'is_return': 0,
                            'remark': '',
                            'final_money': 0,
                            'goods_status': sku.goods_status,
                            'integral_rate': '', //积分倍率
                            'birthday_offers': ''//生日优惠
                        });
                    });

                    var post_data = {};
                    post_data.record = record;
                    post_data.detail = details;
                    post_data.promotion = ProDetail;

                    //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg: post_data, title: 'post_data'});

                    return apiService('pos/pos/add', post_data);
                };

                //新增一张退货小票 ---------------------------------------------
                var add_return = function (data) {
                    //console.log(data);
                    //api.alert({msg:data,title:'add_remote'});
                    //如果没有单据编号则创建 规则为 店铺代码+毫秒时间戳
                    if (typeof data.record_code === "undefined" || data.record_code == '') {
                        //data.record_code = String(shop_code) + String(new Date().getTime());
                        data.record_code = 'LT' + timeStamp2String(0, 'datetime2') + (Math.random() * 9).toFixed(0) + (Math.random() * 9).toFixed(0);
                    }
                    //第一次创建增加制单日期
                    if (typeof data.record_time === "undefined" || data.record_time == '') {
                        data.record_time = timeStamp2String(0, 'datetime');
                    }

                    //****************************************************************************
                    return add_return_remote(data);
                };

                //新增无票退货小票
                var add_no_ticket_return = function (data) {
                    //console.log(data);
                    //如果没有单据编号则创建 规则为 店铺代码+毫秒时间戳
                    //if (typeof data.record_code === "undefined" || data.record_code == '') {
                    data.record_code = 'LT' + timeStamp2String(0, 'datetime2') + (Math.random() * 9).toFixed(0) + (Math.random() * 9).toFixed(0);
                    //}
                    //第一次创建增加制单日期
                    if (typeof data.record_time === "undefined" || data.record_time == '') {
                        data.record_time = timeStamp2String(0, 'datetime');
                    }
                    //****************************************************************************
                    return add_no_ticket_return_local(data).then(function (success) {
                        return add_no_ticket_return_remote(data);
                    });
                };
                //更新本地小票
                var update_record = function (record_code) {
                    //baison_app.api.alert({msg:record_code,title:'record_code'});
                    dbUpdate('PosReceiptRecord', {'is_upload': 1}, {record_code: record_code});//小票主表信息
                };
                //本地无票退货小票
                var add_no_ticket_return_local = function (data) {
                    //组装本地保存数据
                    var record_data = [];
                    record_data.push({
                        'record_code': data['record_code'],
                        'record_time': data['record_time'],
                        'shop_code': $rootScope.current_shop.ShopCode,
                        'trade_user_code': $rootScope.user.UserCode,
                        'customer_code': data['vip']['vip_code'],
                        'vip_code': data['vip']['vip_code'] ? data['vip']['vip_code'] : '',
                        'num': 0 - data.info.total_num, //退货总数量 
                        'money': 0 - data.info.total_money, //退货总金额
                        'init_code': data['init_code'] ? data['init_code'] : '',
                        'pay_money': 0 - (data.info.total_money - (data.info.discount_money)), //支付总金额 data.info.pay_money
                        'change_money': 0.00,
                        'integral': 0,
                        'is_return': 1,
                        'is_checkout': 1,
                        'is_checkout_time': timeStamp2String(0, 'datetime'),
                        'remark': data['reason'] ? data['reason'] : '',
                        'cut_money': 0,
                        'final_money': 0 - (data.info.total_money - (data.info.discount_money)), // 最总支付总金额 等于 支付总金额 （无票退也不需要修改金额） 
                        'lastchanged': timeStamp2String(0, 'datetime'),
                        'is_upload': 0,
                        'discount_money': 0 - (data.info.discount_money), //优惠总金额
                        'deviceId': baison_app.api.deviceId.toString()
                    });
                    //商品明细
                    var insert_details = [];
                    //支付明细
                    var payment = [];
                    $.each(data.list, function (index, sku) {
                        var daogou_name = '';
                        data.guidelist.filter(function (guide) {
                            if (guide.UserCode == sku.daogou) {
                                daogou_name = guide.UserName;
                            }
                        });
                        insert_details.push({
                            'record_code': data.record_code,
                            'detail_index': sku.index,
                            'sku': sku.SkuCode,
                            'goods_code': sku.GoodsCode,
                            'color_code': sku.ColorCode,
                            'size_code': sku.SizeCode,
                            'property_name': sku.SkuPropertyName, //????????????????????????
                            'daogou_code': sku.daogou,
                            'daogou_name': daogou_name,
                            'num': 0 - sku.num,
                            'money': 0 - sku.money,
                            'refer_price': sku.SkuPrice,
                            'price': sku.BuyPrice, //???????????????????
                            'rebate': sku.rebate,
                            'is_return': 1,
                            'remark': '',
                            'final_money': 0 - sku.money,
                            'goods_name': sku.GoodsName,
                            'color_name': sku.ColorName,
                            'size_name': sku.SizeName
                        });


                    });
                    payment.push({
                        'record_code': data.record_code,
                        'trade_type_code': data.trade_type_code,
                        'money': 0 - (data.info.total_money - (data.info.discount_money)), //支付总金额 等于 pay_money  (无票退单一支付方式)
                        'remark': '' + '||' + data.reason,
                        'lastchanged': timeStamp2String(0, 'datetime'),
                        'coupon_code': ''
                    });

                    //促销明细
                    var insert_proDetails = [];
                    if (data['current_promotions'].length !== 0) {
                        $.each(data['current_promotions'], function (i, n) {
                            var ProDetail = {
                                'record_code': data.record_code, //小票单号
                                'pro_record_code': n.record_code, //促销活动单号
                                'short_name': n.short_name, //促销活动简称
                                'promotion_type': n.promotion_type, //促销活动类型
                                'rebate': n.rebate, //促销折扣
                                'reduce_price': n.reduce_price, //促销减金额
                                'gift_total_price': n.gift_total_price,
                                'gift_total_num': n.gift_total_num,
                                'favorable_money': n.favorable_money
                            };
                            insert_proDetails.push(ProDetail);
                            //dbReplace('PosReceiptPromotion', [ProDetail], ['record_code'],['pro_record_code','short_name','promotion_type','rebate','reduce_price','gift_total_price','gift_total_num']);
                        });
                    }

                    //console.log(record_data);
                    //console.log(insert_details);
                    //*******************************************************************************************************************

                    //插入主表
                    return dbReplace('PosReceiptRecord', record_data, ['record_code'], ['record_code', 'record_time', 'shop_code', 'trade_user_code', 'customer_code', 'vip_code', 'num', 'money', 'init_code', 'pay_money', 'change_money', 'integral', 'is_checkout', 'is_checkout_time', 'remark', 'cut_money', 'final_money', 'lastchanged', 'is_upload', 'is_pending'])
                            .then(function (success) {
                                //插入促销明细数据
                                return dbReplace('PosReceiptPromotion', insert_proDetails, ['record_code'], ['pro_record_code', 'short_name', 'promotion_type', 'rebate', 'reduce_price', 'gift_total_price', 'gift_total_num']);
                            })
                            .then(function (success) {
                                //插入详细信息
                                dbReplace('PosReceiptDetail', insert_details, ['detail_index'], ['record_code', 'detail_index', 'sku', 'goods_code', 'goods_name', 'property_name', 'daogou_code', 'num', 'money', 'refer_price', 'price', 'rebate', 'is_return', 'remark', 'final_money']);
                                //插入支付明细
                                dbReplace('PosReceiptSettlement', payment, ['record_code'], ['record_code', 'trade_type_code', 'money', 'coupon_code', 'remark', 'lastchanged']);

                            });
                };



                //服务器无票退货小票
                var add_no_ticket_return_remote = function (data) {
                    //*******************************************************
                    //促销明细
                    var ProDetail = [];
                    if (Object.keys(data['current_promotions']).length !== 0) {
                        $.each(data['current_promotions'], function (i, n) {
                            ProDetail.push({
                                'record_code': data.record_code,
                                'pro_record_code': n.record_code,
                                'short_name': n.short_name,
                                'promotion_type': n.promotion_type,
                                'rebate': n.rebate,
                                'reduce_price': n.reduce_price,
                                'gift_total_price': n.gift_total_price,
                                'gift_total_num': n.gift_total_num,
                                'favorable_money': n.favorable_money
                            });
                        });
                    }


                    //主单信息
                    var record = {};
                    record.record_code = data.record_code;
                    record.record_time = data.record_time;
                    record.vip_code = data.vip.vip_code;
                    record.customer_code = data.vip.vip_code;
                    record.is_return = 1;
                    record.trade_user_code = $rootScope.user.UserCode;
                    record.shop_code = $rootScope.current_shop.ShopCode;
                    record.num = 0 - data.info.total_num; //退货总数量 
                    record.money = 0 - data.info.total_money; //退货总金额
                    record.old_record_code = data.init_code;
                    record.pay_money = 0 - (data.info.total_money - (data.info.discount_money)); // 退货支付总金额 data.info.pay_money
                    record.change_money = 0;
                    record.integral = 0;
                    record.is_checkout = 1;
                    record.is_checkout_time = timeStamp2String(0, 'datetime');
                    record.cut_money = 0;
                    record.final_money = 0 - (data.info.total_money - (data.info.discount_money)); //退货最总支付总金额 等于 退货支付总金额 （退货不需要修改金额）
                    record.discount_money = 0 - (data.info.discount_money); //退货优惠总金额
                    record.lastchanged = timeStamp2String(0, 'datetime');
                    record.sell_time = data.record_time;
                    record.is_add_person = $rootScope.user.UserCode;
                    record.remark = data.reason;
                    record.deviceId = baison_app.api.deviceId.toString();
                    //商品明细
                    var details = [];
                    //商品结算信息
                    //支付明细
                    var payment = [];

                    //退货商品明细
                    $.each(data.list, function (index, sku) {
                        var daogou_name = '';
                        data.guidelist.filter(function (guide) {
                            if (guide.UserCode == sku.daogou) {
                                daogou_name = guide.UserName;
                            }
                        });
                        details.push({
                            'record_code': data.record_code,
                            'detail_index': sku.index,
                            'sku': sku.SkuCode,
                            'goods_code': sku.GoodsCode,
                            'color_code': sku.ColorCode,
                            'size_code': sku.SizeCode,
                            'guide_user_code': sku.daogou,
                            'daogou_code': sku.daogou,
                            'daogou_name': daogou_name,
                            'num': 0 - sku.num,
                            'money': 0 - sku.money,
                            'refer_price': sku.SkuPrice,
                            'price': sku.BuyPrice,
                            'rebate': sku.rebate,
                            'is_return': 1,
                            'remark': '',
                            'final_money': 0 - sku.money

                        });


                    });

                    payment.push({
                        'record_code': data.record_code,
                        'trade_type_code': data.trade_type_code,
                        'money': 0 - (data.info.total_money - (data.info.discount_money)), //支付总金额 等于 退货支付总金额
                        'remark': '',//'' + '||' + data.reason,
                        'lastchanged': timeStamp2String(0, 'datetime'),
                        'coupon_code': ''
                    });
                    var post_data = {};
                    post_data.is_return = 1;
                    post_data.record = record;
                    post_data.detail = details;
                    post_data.payment = payment;
                    post_data.promotion = ProDetail;
                    //console.log(post_data);
                    return apiService('pos/pos/add', post_data);
                };

                //获取退款支付明细
                var get_return_payment_list = function (data) {
                    var payment_list = [];

                    if (data.payment_list.length > 1) { //混合退货 整单退 
                        $.each(data.payment_list, function (i, v) {
                            payment_list.push({
                                'record_code': data.record_code,
                                'trade_type_code': v.trade_type_code,
                                'money': 0 - v.money,
                                'remark': '', //(v.remark == null || v.remark == undefined) ? '' : v.remark + '||' + data.reason,
                                'lastchanged': v.lastchanged,
                                'coupon_code': v.coupon_code,
                                'return_type':false
                            });
                        });
                    } else if (data.payment_list.length == 1) { //单支付方式退货 分单退
                        var payinfo = data.payment_list[0];
                        payment_list.push({
                            'trade_type_code': payinfo.trade_type_code,
                            'money': 0 - data.info.pay_money, // 分单 支付方式 是退货支付金额
                            'remark': '', //(payinfo.remark == null || payinfo.remark == undefined) ? '' : payinfo.remark + '||' + data.reason,
                            'lastchanged': payinfo.lastchanged,
                            'coupon_code': payinfo.coupon_code,
                            'return_type':false
                        });

                    }
                    //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg:payment_list,title:'payment_list'});
                    return payment_list;
                };



                //新增一张退货小票到本地 ---------------------------------------------------------------------------------------------
                var add_return_local = function (data) {

                    //组装本地保存数据
                    var record_data = [];
                    record_data.push({
                        'record_code': data['record_code'],
                        'record_time': data['record_time'],
                        'shop_code': $rootScope.current_shop.ShopCode,
                        'trade_user_code': $rootScope.user.UserCode,
                        'customer_code': data['vip']['vip_code'] ? data['vip']['vip_code'] : '',
                        'vip_code': data['vip']['vip_code'] ? data['vip']['vip_code'] : '',
                        'num': 0 - data.info.total_num, //退货总数量
                        'money': 0 - data.info.total_money, //退货总金额
                        'init_code': data['init_code'] ? data['init_code'] : '',
                        'pay_money': 0 - data.info.pay_money, //退货支付总金额 
                        'change_money': 0.00,
                        'integral': 0,
                        'is_return': 1,
                        'is_checkout': 1,
                        'is_checkout_time': timeStamp2String(0, 'datetime'),
                        'remark': data.reason,//data.allremark ? data.allremark : '',
                        'cut_money': 0,
                        'final_money': 0 - data.info.pay_money, //退货最后金额  退票不需要修改 金额及 等于支付金额 
                        'lastchanged': timeStamp2String(0, 'datetime'),
                        'is_upload': 1,
                        'discount_money': data.discount_money, //退货 优惠金额 （促销 ，套餐，优惠券 ，积分 ，抹零）
                        'deviceId': baison_app.api.deviceId.toString()
                    });


                    //商品明细
                    var insert_details = [];
                    //支付明细
                    //商品结算信息
                    var payment = [];
                    var cur_payment = get_return_payment_list(data);
                    if (cur_payment.length > 1) {
                        payment = cur_payment;
                    }
                    var skuindex = '';
                    var detail_index = '';
                    $.each(data.list, function (index, sku) {
                        //  api.alert({msg:sku,title:'退货商品明细本地'});
                        if (detail_index == sku.detail_index) {
                            skuindex = 't' + sku.detail_index + index;
                        } else {
                            skuindex = 't' + sku.detail_index;
                            detail_index = sku.detail_index;
                        }
                        insert_details.push({
                            'record_code': data.record_code,
                            'detail_index': skuindex,
                            'sku': sku.sku,
                            'goods_name': sku.goods_name,
                            'goods_code': sku.goods_code,
                            'property_name': '', //????????????????????????
                            'daogou_code': sku.guide_user_code,
                            'daogou_name': sku.guide_user_name,
                            'num': 0 - sku.num,
                            'money': 0 - sku.money,
                            'refer_price': sku.refer_price,
                            'price': sku.money, //???????????????????
                            'rebate': sku.rebate,
                            'is_return': 1,
                            'remark': '',
                            'final_money': 0 - sku.money,
                            'color_code': sku.color_code,
                            'size_code': sku.size_code,
                            'color_name': sku.color_name,
                            'size_name': sku.size_name
                        });


                    });
                    //支付方式
                    if (data.payment_list.length == 1) {//分单支付
                        var payinfo = cur_payment[0];
                        payment.push({
                            'record_code': data.record_code,
                            'trade_type_code': payinfo.trade_type_code,
                            'money': payinfo.money, //退货支付金额  
                            'pay_money': payinfo.money, //退票 支付金额 ？可以去掉 
                            'remark': '',
                            'lastchanged': payinfo.lastchanged,
                            'coupon_code': payinfo.coupon_code,
                        });
                    }
                    //退票没有优惠明细 
                    //*******************************************************************************************************************

                    //插入主表
                    return dbReplace('PosReceiptRecord', record_data, ['record_code'], ['record_code', 'record_time', 'shop_code', 'trade_user_code', 'customer_code', 'vip_code', 'num', 'money', 'init_code', 'pay_money', 'change_money', 'integral', 'is_checkout', 'is_checkout_time', 'remark', 'cut_money', 'final_money', 'lastchanged', 'is_upload', 'is_pending'])
                            .then(function (success) {
                                //回写商品明细数据
                                var record_code = data.init_code;
                                var detail_index = '';
                                $.each(data.list, function (index, sku) {
                                    detail_index = sku.detail_index;
                                    dbUpdateAdd('PosReceiptDetail', [{'field': 'is_return', 'value': 1, 'add': 0}, {'field': 'return_num', 'value': sku.num, 'add': 1}], {'record_code': record_code, 'detail_index': detail_index}).then(function (ret) {

                                    });

                                });
                                //插入详细信息
                                dbReplace('PosReceiptDetail', insert_details, ['detail_index'], ['record_code', 'detail_index', 'sku', 'goods_code', 'goods_name', 'property_name', 'daogou_code', 'num', 'money', 'refer_price', 'price', 'rebate', 'is_return', 'remark', 'final_money']);
                                //插入支付明细
                                dbReplace('PosReceiptSettlement', payment, ['record_code'], ['record_code', 'trade_type_code', 'money', 'coupon_code', 'remark', 'lastchanged']);

                            });

                };

                //飞凡退款逻辑 
                var feifan_refund_deal = function(payment,old_record_code){
                    var deferred = $q.defer();
                    var promise = deferred.promise;
                    var feifan = false;
                    payment.forEach(function(n,i){
                        
                        if(n.trade_type_code == '103'){
                        	feifan = true;
                            //baison_app.api.alert({msg:n,title:'feifanpay'});
                            var systype = baison_app.api.systemType;
                            if(systype != 'android'){
                                baison_app.api.toast({msg: $rootScope.language.MSG_FEIFAN_MODULE_NOT_SYS}); //"MSG_FEIFAN_MODULE_NOT_SYS":"只能在android系统上使用",
                                deferred.resolve(false);
                                
                            }
                            var configData = $api.getStorage('configData');
                            if (!configData.feifan.switch) {
                                baison_app.api.toast({msg: $rootScope.language.MSG_FEIFAN_MODULE_NOT_OPEN}); //模块未开启
                                deferred.resolve(false);
                            }
                            if (!baison_app.feifanPay) {
                                baison_app.api.toast({msg: $rootScope.language.MSG_FEIFAN_MODULE_NOT_INSTALL}); //'模块未安装'
                                deferred.resolve(false);
                            }
                            var feifan_param = {
                                extra_pay_order_no: n.coupon_code,
                                extra_pay_amount: (0-n.money)*100,
                                extra_account: "baison001",
                                extra_products: []
                            };
                            //baison_app.api.alert({msg:feifan_param,title:'feifan_param'});
                            //baison_app.api.alert({msg:baison_app.feifanPay,title:'function'});
                            baison_app.feifanPay.refundForResult(feifan_param, function (ret, err) {
                                //baison_app.api.alert({msg:ret,title:'refundForResult'});
                                
                                if (ret.extra_pay_result == 0) {//退款成功
                                	//baison_app.api.alert({msg:'0000000000'});
                                    deferred.resolve(true);
                                }else{
                                	//baison_app.api.alert({msg:'111111111111'});
                                	deferred.resolve(false);
                                }
                                
                                
                            });
                        }
                    });
                    if(!feifan){
                    	deferred.resolve(false);
                    }
                    return promise;
                };

                //新增一张退货小票到服务器 ---------------------------------------
                var add_return_remote = function (data) {
                    //console.log(data.vip);
                    //baison_app.api.alert({msg:data,title:'data Addd1'});
                    //*******************************************************
                    //主单信息
                    var record = {};
                    record.record_code = data.record_code;
                    record.cashNum = $rootScope.cashNum;
                    record.cashDate = $rootScope.cashDate;
                    record.cashStore = $rootScope.cashStore;
                    record.record_time = data.record_time;
                    record.customer_code = data.vip.customer_code;
                    record.vip_code = data.vip.vip_code;
                    record.is_return = 1;
                    record.trade_user_code = $rootScope.user.UserCode;
                    record.shop_code = $rootScope.current_shop.ShopCode;
                    record.num = 0 - data.info.total_num; //退货总数量
                    record.money = 0 - data.info.total_money; // 退货总金额
                    record.old_record_code = data.init_code;
                    record.pay_money = 0 - data.info.pay_money; //退货支付总金额 
                    record.change_money = 0;
                    record.remark = data.reason;
                    record.integral = 0;
                    record.is_checkout = 1;
                    record.is_checkout_time = timeStamp2String(0, 'datetime');
                    record.cut_money = 0;
                    record.final_money = 0 - data.info.pay_money; // 退货 最总 支付总金额  退货 不需要 修改金额 故 为 退货 支付总金额 
                    record.discount_money = data.discount_money; //退货 优惠金额 （促销 ，套餐，优惠券 ，积分 ，抹零）
                    record.lastchanged = timeStamp2String(0, 'datetime');
                    record.sell_time = data.record_time;
                    record.is_add_person = $rootScope.user.UserCode;
                    record.user_code = $rootScope.user.UserCode;
                    record.user_name = $rootScope.user.UserName;
                    record.deviceId = baison_app.api.deviceId.toString();

                    //商品明细
                    var details = [];
                    //商品结算信息
                    //支付明细
                    var payment = [];
                    //baison_app.api.alert({msg:data,title:'data'});
                    var cur_payment = get_return_payment_list(data);
                    //baison_app.api.alert({msg:cur_payment,title:'cur_payment'});
                    if (cur_payment.length > 1) {
                        payment = cur_payment;
                    }
                    //退货商品明细
                    var return_details = [];
                    var skuindex = '';
                    var detail_index = '';
                    $.each(data.list, function (index, sku) {
                        //  alert.alert({msg:sku,title:'退货商品明细'});
                        if (detail_index == sku.detail_index) {
                            skuindex = 't' + sku.detail_index + index;
                        } else {
                            skuindex = 't' + sku.detail_index;
                            detail_index = sku.detail_index;
                        }

                        details.push({
                            'record_code': data.record_code,
                            'detail_index': skuindex,
                            'sku': sku.sku,
                            //'property_name':sku.SkuPropertyName,
                            'goods_code': sku.goods_code,
                            'color_code': sku.color_code,
                            'size_code': sku.size_code,
                            'guide_user_code': sku.guide_user_code,
                            'daogou_code': sku.guide_user_code,
                            'daogou_name': sku.guide_user_name,
                            'num': 0 - sku.num,
                            'money': 0 - sku.money,
                            'refer_price': sku.refer_price,
                            'price': sku.price,
                            'rebate': sku.rebate,
                            'is_return': 1,
                            'remark': data.allremark ? data.allremark : '',
                            'final_money': 0 - sku.money
                        });

                        return_details.push({
                            'num': sku.num,
                            'detail_index': sku.detail_index,
                        });

                    });

                    //支付方式
                    if (data.payment_list.length == 1) {
                        var payinfo = cur_payment[0];
                        payment.push({
                            'record_code': data.record_code,
                            'trade_type_code': payinfo.trade_type_code,
                            'money': payinfo.money, //退货支付金额 
                            'pay_money': payinfo.money,
                            'remark': payinfo.remark,
                            'lastchanged': payinfo.lastchanged,
                            'coupon_code': payinfo.coupon_code,
                            'return_type':false
                        });
                    }
                    var deferred = $q.defer();
                    var promise = deferred.promise;
                    feifan_refund_deal(payment,record.old_record_code).then(function(ret){
                        //baison_app.api.alert({msg:ret,title:'ret'});
                        var post_data = {};
                        post_data.record = record;
                        post_data.detail = details;
                        post_data.payment = payment;
                        post_data.is_return = 1;
                        if(ret){
                        	post_data.payment.forEach(function(n){
								if(n.trade_type_code == '103'){
									n.return_type = true;
								}
							});
                        }
                        //console.log(post_data);
                        //baison_app.api.alert({msg:post_data.payment,title:"payment"});
                        apiService('pos/pos/add', post_data).then(function(addata){
                            if(addata.data.status == 1){
                                var detail_data = {};
                                detail_data.record_code = data.init_code;
                                detail_data.record_detail = return_details;
                                //更新小票主单据到服务器

                                apiService('pos/pos/update_receipt', {'is_return': 1, 'record_code': data.init_code, 'return_num': data.info.total_num}).then(function (ret) {

                                    if (ret.data.status == 1) {
                                        //更新明细小票单据到服务器
                                        apiService('pos/pos/update_receipt_detail', detail_data).then(function(ret){
                                             add_return_local(data);
                                             deferred.resolve(addata);
                                        });
                                    }

                                });
                            }else{
                                deferred.resolve(addata);
                            }
                            
                        }).catch(function(err,success){
                            deferred.resolve(err);
                            baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_NOT_CONNECTED_INTERNET}); //'没有联网'

                        });
                        
                    });
                    
                    return promise;
                    
                };


                //根据单号更新一张小票内容或状态 ---------------------------------
                var pay = function (record_code, data) {
                    $.each($rootScope.goods_cart.checklist,function(i,n){
                        if(n.code == '003' && $rootScope.goods_cart.info.discount_money != 0){
                             n.pay_money=(n.pay_money*1) > ($rootScope.goods_cart.info.discount_money*1)?$rootScope.goods_cart.info.discount_money:n.pay_money;
                             n.final_money=(n.final_money*1)>($rootScope.goods_cart.info.discount_money*1)?$rootScope.goods_cart.info.discount_money:n.final_money;
                                
                        }
                    });
                    //console.log(data.info);
                    return pay_local(record_code, data).then(function (success) {
                        return pay_remote(record_code, data);
                    });
                };
                //本地支付 ----------------------------------------------------
                var pay_local = function (record_code, data) {
                    var now = timeStamp2String(0, 'datetime');
                    //更新支付列表
                    if (typeof data.checklist !== 'undefined' && data.checklist.length >= 0) {
                        var payData = [];
                        data.checklist.forEach(function (e, index) {

                            var info = {
                                'record_code': record_code,
                                'trade_type_code': e.code,
                                'money': e.final_money,
                                'coupon_code': e.coupon_code,
                                'remark': e.remark,
                                'lastchanged': now
                            };
                            payData.push(info);
                        });

                    }
                    var money = 0;
                    data.list.forEach(function (e, index) {
                        money = money + e.BuyPrice * e.num;
                    });

                    //更新主表信息
                    var final_money = data.info.need_money;
                    var pay_money = data.info.pay_money;
                    var change_money = data.info.change_money;
                    var allremark = data.allremark ? data.allremark : '';
                    var record_info = {
                        'is_checkout': 1,
                        'is_checkout_time': now,
                        'pay_money': pay_money,
                        'change_money': change_money,
                        'final_money': final_money,
                        'money': money,
                        'is_upload': 0,
                        'user_name': $rootScope.user.UserName,
                        'user_code': $rootScope.user.UserCode,
                        'remark': allremark
                    };

                    return dbInsertMulti('PosReceiptSettlement', payData).then(function (success) {//小票单据结算信息
                        return dbUpdate('PosReceiptRecord', record_info, {record_code: record_code});//小票主表信息
                    });
                };
                //服务器更新 --------------------------------------------------
                var pay_remote = function (record_code, data) {
                    //组装数据
                    var allremark = data.allremark ? data.allremark : '';
                    var post_data = {};
                    post_data.record_code = record_code;
                    post_data.payment = [];
                    data.checklist.forEach(function (e, index) {
                        //  api.alert({msg:data.allremark,title:'data.allremark'});
                        post_data.payment.push({
                            'trade_type_code': e.code,
                            'money': e.final_money,
                            'coupon_code': e.coupon_code,
                            'remark': e.remark,
                            'pay_money': e.pay_money
                        });
                    });
                    var money = 0;
                    data.list.forEach(function (e, index) {
                        money = money + e.BuyPrice * e.num;
                    });
                    //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg:data.info,title:'info'});
                    data.info.money = money;
                    post_data.record = data.info;
                    post_data.record.shop_code = $rootScope.current_shop.ShopCode;
                    post_data.record.user_code = $rootScope.user.UserCode;
                    post_data.record.user_name = $rootScope.user.UserName;
                    post_data.record.vip_code = data.vip.vip_code;
                    post_data.record.customer_code = data.vip.customer_code;
                    post_data.record.customer_name = data.vip.customer_name;
                    post_data.record.remark = allremark;
                    post_data.record.deviceId = baison_app.api.deviceId;
                    post_data.record.final_money = post_data.record.need_money; //设备唯一标识，字符串类型 post_data.device_sn
                    //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg:post_data.payment,title:'789999'});
                    //提交远程接口
//                    baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg: post_data, title: 33333});

                    return get_one_local(record_code).then(function (record_data) {
                        //将小票的所有信息都传到后台
                        post_data.record_data = record_data;

                        //console.log(JSON.stringify(record_data));
                        //baison_app.api.alert({title:'dedd',msg:post_data});
                        //console.log(post_data);
                        return apiService('pos/pos/update', post_data).then(function (success) {
                            if (success.data.status == 1) {
                                //更新本地状态为已同步
                                dbUpdate('PosReceiptRecord', {'is_upload': 1}, {record_code: record_code});
                            }
                            return success;
                            //baison_app.api.alert({title:'gfgfdg',msg:success});
                        });
                    });
                };

                //清除本地无用小票: 如本地未结算的前一天挂单的 --------------------
                var clear = function () {

                };
                //优惠券
                var youhuiquan_add = function (param) {
                    return apiService('crm/coupon/get_coupon', param);
                };
                //vip积分
                var vipjifen_add = function (param) {
                    return apiService('crm/integral/integral_change_money', param);
                };
                //作废未上传小票 服务器操作
                var receipt_cancel = function (param) {
                    return apiService('pos/pos/receipt_cancel', param);
                };
                //作废未上传小票 本地操作
                var receipt_cancel_local = function (param) {
                    //删除本地小票主表信息
                    return dbDelete('PosReceiptRecord', param).then(function (ret) {
                        return dbDelete('PosReceiptDetail', param);
                    });

                };
                //更新库存 type 为1 退货  为0 支付
                var update_skunum = function (goods_list, type) {
					
						//汇总skucode 的值 去重skucode
					var sku_list = [];
				    var hash = {};
					var elem = '';

					$.each(goods_list,function(i,n){
						elem = n.SkuCode ? n.SkuCode : n.sku;
						if(elem !=null){
							if (!hash[elem]) {
								sku_list.push({'SkuCode':elem,'num':n.num});
								hash[elem] = true;
							}else{
								for(var j = 0; j<sku_list.length;j++){
									if(sku_list[j].SkuCode == (n.SkuCode?n.SkuCode:n.sku)){
										sku_list[j].num += n.num;
									}
								}
							}
						}
					});
					

                    var SkuCode = '';
                    var SkuNum = '';
                    $.each(sku_list, function (i, n) {
                        SkuCode = n.SkuCode ? n.SkuCode : n.sku;
                        SkuNum = n.num;
                        if (type) {
                            //本地
							//console.log(SkuNum);
                            ruKu.update_local_SkuNum(SkuCode, SkuNum);
                            //服务器 讨论后去掉
                            //ruKu.update_service_SkuNum(SkuCode, SkuNum);
                        } else {
                            //本地
                            ruKu.update_local_SkuNum(SkuCode, -SkuNum);
                            //服务器 讨论后去掉
                            //ruKu.update_service_SkuNum(SkuCode, -SkuNum);
                        }

                    });

                };
                //热销商品 时间点
                var get_hot_goods = function (day, search_type) {
                    //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg:day,title:'day'});
                    var sql = ' select p.goods_name, p.goods_code, p.sku, sum(p.num) num, sum(p.money) money '
                            + ' from PosReceiptDetail p '
                            + ' inner join PosReceiptRecord r on r.record_code = p.record_code '
                            + ' where r.record_time >= "' + day + '" and r.is_return=0 and r.is_checkout=1 '
                            + ' group by p.sku order by sum(p.' + search_type + ') desc limit 10 ';
                    //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg:sql,title:'sql'});   
                    return dbSelect('YsPos', sql);

                };
                //热销商品时间段
                var get_hot_goods_by_time = function (start, end, search_type) {
                    end = timeStamp2String(end, 'date');
                    end = end.concat(" ");
                    end = end.concat("23:59:59");
                    end = timeStamp2String(end, 'datetime');
                    var sql = ' select p.goods_name, p.goods_code, p.sku, sum(p.num) num, sum(p.money) money '
                            + ' from PosReceiptDetail p '
                            + ' inner join PosReceiptRecord r on r.record_code = p.record_code '
                            + ' where r.record_time >= "' + start + '"and r.record_time <"' + end + '" and r.is_return=0 and r.is_checkout=1 '
                            + ' group by p.sku order by sum(p.' + search_type + ') desc limit 10 ';

                    return dbSelect('YsPos', sql);

                };
                //导购业绩时间点
                var get_cash_by_daogou = function (day, search_type) {
                    var num = 0;
                    var money = 0.00;
                    var sql = ' select p.daogou_code,u.UserName, sum(p.num) num, sum(p.money) money '
                            + ' from PosReceiptDetail p '
                            + ' inner join PosReceiptRecord r on r.record_code = p.record_code '
                            + ' inner join PosUser u on u.UserCode = p.daogou_code '
                            + ' where r.record_time >= "' + day + '" and  r.is_return=0 and r.is_checkout=1 ';
                    sql += ' group by p.daogou_code order by sum(p."' + search_type + '") desc ';

                    return dbSelect('YsPos', sql);
                };
                //导购业绩时间段
                var get_cash_by_daogou_by_time = function (start, end, search_type) {
                    end = timeStamp2String(end, 'date');
                    end = end.concat(" ");
                    end = end.concat("23:59:59");
                    end = timeStamp2String(end, 'datetime');
                    var num = 0;
                    var money = 0.00;
                    var sql = ' select p.daogou_code,u.UserName, sum(p.num) num, sum(p.money) money '
                            + ' from PosReceiptDetail p '
                            + ' inner join PosReceiptRecord r on r.record_code = p.record_code '
                            + ' inner join PosUser u on u.UserCode = p.daogou_code '
                            + ' where   r.is_return=0 and r.is_checkout=1 ';


                    sql += ' and r.record_time >= "' + start + '"';


                    sql += ' and r.record_time <= "' + end + '"';

                    sql += ' group by p.daogou_code order by sum(p.' + search_type + ') desc ';

                    return dbSelect('YsPos', sql);
                };
                //注意退票的逻辑
                
                // 导购员：根据取销售小票内的导购员姓名 
                // 销售额：根据时段内取该导购的销售实付金额 
                // 销售量：根据时段内取该导购的销售数量 
                // 连带率：根据时段内计算该导购的销售数量（销售的商品数量）/销售小票数 
                // 新增会员数：根据时段内取该导购发卡数量 （是否是上传到服务器的新增会员数量）
                    //一段时间内新增的会员，只显示本店的，暂时从本店的离线会员数据里面获取
                // 会员购买比例：根据时段内计算属于该导购的会员购买金额/总营业额
                 
                //业务小结列表数据根据时间
                var get_salesdata_by_daogou = function(day,start,end){ //从服务器上获取
                    //console.log(day);
                    var params = {};
                    params['is_checkout'] = 1;
                    params['shop_code'] = $rootScope.current_shop.ShopCode;
                    if(day != ''){
                        params['day'] = day;
                    }else{
                        params['start'] = start;
                        end = timeStamp2String(end, 'date');
                        end = end.concat(" ");
                        end = end.concat("23:59:59");
                        end = timeStamp2String(end, 'datetime');
                        params['end'] = end;
                    }
                    var sales_info_list = {}; //业务小结列表信息
                    return apiService('pos/pos/get_record_by_time', params).then(function(ret){
                        var deferred = $q.defer();
                        var promise = deferred.promise;
                        if(ret.data.status == 1){ //返回成功
                            data = ret.data.data; //符合条件的小票信息 (各个小票的信息)
                            data.forEach(function(record){
                                var m_record = record.record;
                                //获取该单小票实际支付金额
                                var payment = record.payment;
                                var real_pay_total_money = 0;
                                var record_money = parseFloat(m_record.final_money); //实际支付金额
                                var total_money = parseFloat(m_record.money); //商品总价
                                var record_num = parseInt(m_record.num);      //商品总数量
                                var is_vip = (m_record.vip_code == "" || m_record.vip_code == undefined)?false:true;
                                var usercode = m_record.guide_user_code; 
                                var real_num = record_num;
                                var last_real_money = record_money;
                                var userkeys = Object.keys(sales_info_list);
                                var index = userkeys.indexOf(usercode);
                                if(userkeys.length == 0 || index == -1 ) {//购买列表没有信息
                                    sales_info_list[usercode] = {};
                                    sales_info_list[usercode].goods_num = parseFloat(real_num);
                                    sales_info_list[usercode].real_pay_money = last_real_money;
                                    console.log(sales_info_list[usercode].real_pay_money);
                                    sales_info_list[usercode].record_num = 1; //小票数量（为计算连带率做准备）
                                    sales_info_list[usercode].vip_pay_money = parseFloat((is_vip)?sales_info_list[usercode].real_pay_money:0);//会员购买支付金额（为计算会员购买比例做准备）
                                         
                                }else{
                                    sales_info_list[usercode].goods_num = parseFloat(parseInt(sales_info_list[usercode].goods_num) + real_num);
                                    sales_info_list[usercode].real_pay_money = parseFloat(sales_info_list[usercode].real_pay_money) + last_real_money;
                                    sales_info_list[usercode].record_num = parseFloat(parseInt(sales_info_list[usercode].record_num) + 1); //小票数量（为计算连带率做准备）
                                    sales_info_list[usercode].vip_pay_money = parseFloat(sales_info_list[usercode].vip_pay_money)+parseFloat((is_vip)?last_real_money:0);//会员购买支付金额（为计算会员购买比例做准备）
                                }
                                //从小票详情中获取导购员信息
                                var record_detail = record.record_detail;
                                record_detail.forEach(function(info){
                                    sales_info_list[usercode].daogou_name = info.guide_user_name;
                                });
                            });
                        }
                        //console.log(realmoney);
                        //console.log(nomoney);
                        //console.log(sales_info_list);  
                        deferred.resolve(sales_info_list);
                        return promise;
                        
                    }); 
                      
                };
                
                
                //获取支付列表信息
                var get_payment_list = function(day,start,end){//从服务器上获取
                    //小票信息，小票详情,小票支付信息 （并集） trade_name  trade_money
                    var params = {};
                    params['is_checkout'] = 1;
                    params['shop_code'] = $rootScope.current_shop.ShopCode;
                    if(day != ''){
                        params['day'] = day;
                    }else{
                        params['start'] = start;
                        end = timeStamp2String(end, 'date');
                        end = end.concat(" ");
                        end = end.concat("23:59:59");
                        end = timeStamp2String(end, 'datetime');
                        params['end'] = end;
                    }
                    var configData = $api.getStorage('configData');
                    var checklist = configData.checklist;
                    var tradename = [];
                    checklist.forEach(function(trade_code){ //本地查询快于请求服务器
                        checkGetList.get_name_by_code(trade_code).then(function (ret) {
                            tradename.push(ret[0].CheckName);
                        });
                    });
                    var payment_list= {};//支付信息
                    return apiService('pos/pos/get_detail_by_time', params).then(function(ret){
                        //console.log(ret);
                       
                        var deferred = $q.defer();
                        var promise = deferred.promise;

                        if(ret.data.status == 1){ //返回成功
                            data = ret.data.data; //符合条件的小票信息 (各个小票的支付信息)
                            //console.log(data);
                            data.forEach(function(settleinfo){
                                settleinfo.forEach(function(n){
                                    //判断该支付方式是否在当前选择支付方式中
                                    var index = checklist.indexOf(n.trade_type_code);
                                    if(index != -1){ //当前选择的有该支付方式
                                        if(payment_list[n.trade_type_code] == undefined){
                                            payment_list[n.trade_type_code] = {};
                                            payment_list[n.trade_type_code].trade_money = parseFloat(n.money);
                                            payment_list[n.trade_type_code].trade_name = tradename[index];
                                        }else{
                                            payment_list[n.trade_type_code].trade_money = parseFloat(payment_list[n.trade_type_code].trade_money+parseFloat(n.money));
                                        }
                                    }
                                    
                                });
                            });
                        }
                        //console.log(payment_list);
                        deferred.resolve(payment_list);
                        return promise;
                    });
                };
                
                
                
                //零售日分析按商品
                var get_goodsname_by_day = function (start, end, search_type, goodscode) {
                    end = timeStamp2String(end, 'date');
                    end = end.concat(" ");
                    end = end.concat("23:59:59");
                    end = timeStamp2String(end, 'datetime');
                    var sql = ' select p.sku,p.goods_name,sum(p.num) num, sum(p.money) money ,r.record_time '
                            + ' from PosReceiptDetail p '
                            + ' inner join PosReceiptRecord r on r.record_code = p.record_code '
                            + ' where r.record_time >= "' + start + '" and r.record_time <="' + end + '" and r.is_return=0 and r.is_checkout=1 '
                            + ' and p.goods_code = "' + goodscode + '" '
                            + ' group by p.sku,r.record_time  order by r.record_time,sum(p.' + search_type + ')  desc';

                    return dbSelect('YsPos', sql);


                };
                //根据用户输的code模糊查询goodscode
                var get_sku_by_goodscode = function (start, end, goodscode) {
                    return BaseGoods.get_sku_by_code(goodscode).then(function (ret) {
                        goodscode = ret[0].GoodsCode;
                        end = timeStamp2String(end, 'date');
                        end = end.concat(" ");
                        end = end.concat("23:59:59");
                        end = timeStamp2String(end, 'datetime');
                        var sql = ' select p.goods_name,p.goods_code,p.sku '
                                + ' from PosReceiptDetail p '
                                + ' inner join PosReceiptRecord r on r.record_code = p.record_code '
                                + ' where r.record_time >= "' + start + '" and r.record_time <="' + end + '" and r.is_return=0 and r.is_checkout=1 '
                                + ' and p.goods_code like "%' + goodscode + '" '
                                + ' group by p.goods_code order by r.record_time desc';
                        return dbSelect('YsPos', sql);
                    });


                };
                //零售日分析按分类
                var get_goodsname_by_type = function (start, end, search_type, cate, sort) {
                    end = timeStamp2String(end, 'date');
                    end = end.concat(" ");
                    end = end.concat("23:59:59");
                    end = timeStamp2String(end, 'datetime');

                    var sql = ' select p.goods_name,sum(p.num) num, sum(p.money) money ,r.record_time  '
                            + ' from PosReceiptDetail p '
                            + ' inner join PosReceiptRecord r on r.record_code = p.record_code '
                            + ' inner join PosGoods g on g.GoodsCode = p.goods_code'
                            + ' inner join PosSku k on g.GoodsCode = k.GoodsCode'
                            + ' where r.record_time >= "' + start + '" and r.record_time <="' + end + '" and r.is_return=0 and r.is_checkout=1 '
                            + ' and g.CategoryCode="' + cate + '" and g.SortCode="' + sort + '"'
                            + ' group by p.goods_name,r.record_time  order by r.record_time , sum(p.' + search_type + ') desc';

                    return dbSelect('YsPos', sql);

                };
                //第三方支付退款
                var third_pay_return = function(param){
                    return apiService('pos/pos/third_pay_return', param);
                };
                //第三方支付 查询（第三方支付反应慢 导致没有结算）
                var third_pay_query = function(param){
                    return apiService('pos/pos/third_pay_query', param);
                };
                return {
                    add: add,
                    add_local: add_local,
                    add_remote: add_remote,
                    add_return: add_return,
                    add_return_local: add_return_local,
                    add_return_remote: add_return_remote,
                    add_no_ticket_return: add_no_ticket_return,
                    pay: pay,
                    pay_local: pay_local,
                    pay_remote: pay_remote,
                    clear: clear,
                    get_one: get_one,
                    get_one_local: get_one_local,
                    get_list: get_list,
                    get_list_local_not_upload: get_list_local_not_upload,
                    get_list_local_offline: get_list_local_offline,
                    get_list_local: get_list_local,
					get_return_list_local:get_return_list_local,
                    get_day: get_day,
                    youhuiquan_add: youhuiquan_add,
                    vipjifen_add: vipjifen_add,
                    receipt_cancel: receipt_cancel,
                    receipt_cancel_local: receipt_cancel_local,
                    update_skunum: update_skunum,
                    get_hot_goods: get_hot_goods,
                    get_hot_goods_by_time: get_hot_goods_by_time,
                    get_cash_by_daogou: get_cash_by_daogou,
                    get_cash_by_daogou_by_time: get_cash_by_daogou_by_time,
                    get_salesdata_by_daogou:get_salesdata_by_daogou,
                    get_payment_list:get_payment_list,
                    get_goodsname_by_day: get_goodsname_by_day,
                    get_goodsname_by_type: get_goodsname_by_type,
                    get_sku_by_goodscode: get_sku_by_goodscode,
                    update_record: update_record,
                    third_pay_return:third_pay_return,
                    third_pay_query:third_pay_query
                };
            }
        ])
        //微信支付方式相关操作
        .factory('WeiXin_ZF', ['$rootScope', '$q', 'apiService', 'timeStamp2String', 'jsonToXml', 'xmlToJson', 'dbReplace', 'dbInsertMulti', 'dbUpdate', 'dbSelect', function ($rootScope, $q, apiService, timeStamp2String, jsonToXml, xmlToJson, dbReplace, dbInsertMulti, dbUpdate, dbSelect) {
                //微信相关设置
                //微信扫码
                var weixin_scan_pay = function (param) {
                    param.shop_code = $rootScope.current_shop.ShopCode;
                    return apiService('weixin/weixin/scan_pay_2', param);
                };
                var weixin_orderquery = function (param) {
                    param.shop_code = $rootScope.current_shop.ShopCode;
                    return apiService('weixin/weixin/ordertradequery', param);
                };

                var weixin_cancel_trade = function (param) {
                    param.shop_code = $rootScope.current_shop.ShopCode;
                    return apiService('weixin/weixin/cancel_trade', param);
                };

                //微信刷卡
                var weixin_tiaoma_trade = function (param) {
                    var data = {};
                    data.device_info = $rootScope.current_shop.ShopCode;
                    data.body = param.body;
                    data.out_trade_no = param.record_code;
                    data.total_fee = param.daifu;
                    data.spbill_create_ip = '8.8.8.8';
                    data.auth_code = param.auth_code;
                    data.shop_code = $rootScope.current_shop.ShopCode;
                    data.shop_guide = param.shop_guide;
                    return apiService('weixin/weixin/tiaoma_pay', data);
                }

                return {
                    weixin_scan_pay: weixin_scan_pay,
                    weixin_orderquery: weixin_orderquery,
                    weixin_cancel_trade: weixin_cancel_trade,
                    weixin_tiaoma_trade: weixin_tiaoma_trade

                };
            }
        ])
        //支付宝支付方式相关操作
        .factory('ZhiFuBao_ZF', ['$rootScope', '$q', 'apiService', 'timeStamp2String', 'jsonToXml', 'xmlToJson', 'dbReplace', 'dbInsertMulti', 'dbUpdate', 'dbSelect', function ($rootScope, $q, apiService, timeStamp2String, jsonToXml, xmlToJson, dbReplace, dbInsertMulti, dbUpdate, dbSelect) {
                //支付宝预下单 （获取二维码）
                var saoma_scan_pay = function (param) {
                    param.shop_code = $rootScope.current_shop.ShopCode;
                    return apiService('zhifubao/zfb_saoma/scan_pay', param);

                };
                //支付宝条码支付
                var tiaoma_pay = function (param) {
                    param.shop_code = $rootScope.current_shop.ShopCode;
                    return apiService('zhifubao/zfb_tiaoma/scan_pay', param);
                };
                //支付宝 查询订单
                var orderquery = function (param) {
                    param.shop_code = $rootScope.current_shop.ShopCode;
                    return apiService('zhifubao/zfb_public_operate/ordertradequery', param);
                };
                //支付宝 撤销订单
                var ordercancel = function (param) {
                    param.shop_code = $rootScope.current_shop.ShopCode;
                    return apiService('zhifubao/zfb_public_operate/cancel_trade', param);
                };

                return {
                    saoma_scan_pay: saoma_scan_pay,
                    tiaoma_pay: tiaoma_pay,
                    orderquery: orderquery,
                    ordercancel: ordercancel
                };
            }])
        //小票模版打印
        .factory('Print', ['$rootScope', '$q', 'apiService', 'timeStamp2String', 'jsonToXml', 'xmlToJson', 'dbReplace', 'dbInsertMulti', 'dbUpdate', 'dbSelect', 'BaseGoods', 'dbGetOneSync', function ($rootScope, $q, apiService, timeStamp2String, jsonToXml, xmlToJson, dbReplace, dbInsertMulti, dbUpdate, dbSelect, BaseGoods, dbGetOneSync) {
                //根据小票模版tpl_name 获取小票内容
                var xp_select_tplcontent = function (id) {
                    var sql = 'select content from Pos_xiaopiao_templates where id = "' + id + '"';

                    var content = dbSelect('YsPos', sql);

                    return content;
                };
                var stock_select_tplcontent = function (id) {
                    var sql = 'select content from Pos_stock_templates where id = "' + id + '"';

                    var content = dbSelect('YsPos', sql);

                    return content;
                };
                var stock_select_tplname = function (id) {
                    var sql = 'select name,id from Pos_xiaopiao_templates';
                    var name = dbSelect('YsPos', sql);
                    return name;

                };
                //获取小票名称
                var xp_select_tplname = function () {
                    var sql = 'select name,id from Pos_xiaopiao_templates';
                    var name = dbSelect('YsPos', sql);
                    return name;
                };
                //打印蓝牙配对
                var bluetooth = function () {
                    if (baison_app.printmodule != undefined && baison_app.printmodule != null) {
                        baison_app.printmodule.showBluetoothSetView({}, function (ret, err) {
                            var names = '';
                            if (ret.name != undefined) {
                                names = $rootScope.language.TIP_RECEIPR_EQUIPMENT + ret.name;
                            } else {
                                names = $rootScope.language.TIP_RECEIPR_EQUIPMENT_LACK;
                            }
                            baison_app.api.alert({msg: names, buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.TIPS_SET_BLUETOOTG_PAIR});
                            return names;
                        });
                    } else {
                        baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT, buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT});
                        return;

                    }

                };

                //added by lqx on 20170111 判断状态转换为文字
                var check_ico_for_print =function(input){
                    if (input == 1 || input == '1') {
                        return $rootScope.language.TIP_AUDITED/*'已审核'*/;
                    } else if (input == 0 || input == '0') {
                        return $rootScope.language.TIP_NOT_AUDITED/*'未审核'*/;
                    } else {
                        return '?';
                    }
                };
                var check_is_sure_for_print = function (input) {
                    if (input == 1 || input == '1') {
                        return $rootScope.language.TIP_CONFIRMED/*'已确认'*/;
                    } else if (input == 0 || input == '0') {
                        return $rootScope.language.TIP_UNCONFIRMED/*'未确认'*/;
                    } else {
                        return '?';
                    }
                };
                var check_is_allocate_for_print = function (input) {
                    if (input == 1 || input == '1') {
                        return $rootScope.language.TIP_HAVE_OUTBOUND/*'已出库'*/;
                    } else if (input == 0 || input == '0') {
                        return $rootScope.language.TIP_NOT_OUTBOUND/*'未出库'*/;
                    } else {
                        return '?';
                    }
                };
                var check_is_stock_in_for_print = function (input) {
                    if (input == 1 || input == '1') {
                        return '已入库';
                    } else if (input == 0 || input == '0') {
                        return '未入库';
                    } else {
                        return '?';
                    }
                };

                //小票打印
                var xp_print = function (title, record) {
                    var deferred = $q.defer();
                    var promise = deferred.promise;
                    var systype = baison_app.api.systemType;
                    var configData = $api.getStorage('configData');
                    var pay_type = configData.zftd;
                    var printData = configData.printData;

                    if (systype == 'ios') {
                        if (baison_app.boxPay == undefined || baison_app.boxPay == null) {
                            baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT});
                            deferred.resolve('success');
                            return;
                        }
                    } else if (systype == 'android') {
                        if ((baison_app.usbPrint == undefined || baison_app.usbPrint == null) && (baison_app.printmodule == undefined || baison_app.printmodule == null)) {
                            baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT});
                            deferred.resolve('success');
                            return;
                        } else if (printData != undefined) {
                            var usb = printData['usb'];
                            if (usb == 1) {
                                if (baison_app.usbPrint == undefined || baison_app.usbPrint == null) {
                                    baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT});
                                    deferred.resolve('success');
                                    return;
                                }
                            }
                        }
                    }

                    //var configData = $api.getStorage('configData');
                    //var printData = configData.printData;
                    //从配置文件里获取小票模版名称
                    var tpl_name = '';
                    if (printData != undefined) {
                        tpl_name = printData['selectvalue'];
                    }

                    //根据小票模版tpl_name 获取小票内容
                    var tpl_content = '';

                    xp_select_tplcontent(tpl_name).then(function (ret) {
						
                        if (ret[0] != undefined && ret[0].content != undefined && ret[0].content != null) {
                            tpl_content = ret[0].content;
                        }
                        xp_print_tpl_to_string(title, tpl_content, record, function (data) {
                            //引用打印模块
                            //判断是否是盒子支付方式
                            //var systype = baison_app.api.systemType;
                            if (systype == 'ios') { //盒子支付 暂时支持ios
                                //var configData = $api.getStorage('configData');
                                //var pay_type = configData.zftd;
                                if (pay_type == 1) { //是盒子支付
                                    if (baison_app.boxPay != undefined && baison_app.boxPay != null) {
                                        baison_app.boxPay.printOrder({orderTitle: record.record_code, shop: record.shop_name, text: data}, function (ret, err) {
                                            //无返回
											deferred.resolve('success');
                                        });
                                    }
                                    
                                    return;
                                }
                            }

                            //判断是否是usb接口打印
                            if (systype == 'android') {
                                //var configData = $api.getStorage('configData');
                                //var printData = configData.printData;
                                if (printData != undefined) {
                                    var usb = printData['usb'];
                                    if (usb != undefined && usb != null && usb == 1) {
                                        //进行usb打印
                                        if (baison_app.usbPrint != undefined && baison_app.usbPrint != null) {
                                            var param = {text: data};
                                            baison_app.usbPrint.printText(param, function (ret, err) {
                                                //baison_app.api.alert({msg: ret, title: 'usb打印'});
												deferred.resolve('success');
                                            });
                                        }
                                        
                                        return;
                                    }
                                }
								var configData = $api.getStorage('configData');
								//baison_app.api.alert({msg:configData,title:'configData'});
								if(configData.feifan.switch==1 && configData.feifan.feifan == 1){
									//baison_app.api.alert({msg:'feifan'});
                                    //非凡打印
                                    baison_app.feifanPrint.selectDevice(function(){//开启打印机
                                        var param = {text: data};
										//baison_app.api.alert({msg: param, title: 'param'});
                                        //开始打印
                                        baison_app.feifanPrint.printText(param, function (ret, err) {
                                            //baison_app.api.alert({msg: ret, title: '飞凡打印'});
                                            if(ret.messagePrint==1){//打印成功后切纸
                                                //切纸
                                                baison_app.feifanPrint.cutePaper(function(ret,err){
                                                    //baison_app.api.alert({title: "切纸",msg:ret});
                                                    //关闭打印机
                                                    baison_app.feifanPrint.closeDevice(function (ret, err) {
														deferred.resolve('success');
                                                    });
                                                });
                                            }

                                        });
                                    });
                                    
                                    return;
                                }

                            }
                            var configData = $api.getStorage('configData');
                            var printData = configData.printData;
							var usb = printData['usb'];
							if(configData.feifan.switch!=1 && usb != 1) {
                                if (baison_app.printmodule != undefined && baison_app.printmodule != null) {
                                    baison_app.printmodule.getDevice({}, function (ret, err) {

                                        if (ret.deviceName == undefined) {
                                            baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT_BLUE});
                                            return;
                                        }
                                    });
                                }
                            }
                            //不是盒子支付方式
                            if (baison_app.printmodule != undefined && baison_app.printmodule != null) {
                                baison_app.printmodule.getDevice({}, function (ret, err) {

                                    var param = {text: data};
                                    baison_app.printmodule.printText(param, function (ret, err) {
										deferred.resolve('success');

                                        //baison_app.api.alert({msg: ret, title: '打印'});
                                        //aison_app.api.alert({msg: err, title: '打印失败'});
                                    });

                                });
                            }
                            
                            return;
                        });
                    });
                    return promise;
                };

                /**
                 * 小票模版转换为打印内容
                 * @author jhua.zuo<jhua.zuo@baisonmail.com>
                 * @date 2015-08-11
                 * @param {String} tpl 小票模版内容
                 * @param {Object} record 小票模版变量
                 * @returns {undefined}
                 */
                var xp_print_tpl_to_string = function (title, tpl_content, record, callback) {
                    //baison_app.api.alert({msg:record,title:'record'});
                    // 没有选择模版时 默认的模版 
                    if (tpl_content == '') {
                        tpl_content = tpl_content ='欢迎光临 $brand_name$\r\n' +
                                '柜台：$shop_name$\r\n' +
                                '日期：$record_time$\r\n' +
                                '================================\r\n' +
                                '导购员：$guide_name$\r\n' +
                                '会员卡号：$vip_code$\r\n' +
                                '单号：$record_code$\r\n' +
                                '-商品清单---------------------\r\n' +
                                '商品名称：\r\n'+
                                '商品编码：\r\n'+
                                '单价:      数量:     金额: \r\n'+
                                '----------------------------\r\n' +
                                '{商品}\r\n' +
                                '#goods_name#(#unit_name#/#weight#)\r\n' +
                                '#sku_name#\r\n' +
                                '#price#     #num#     #money#\r\n' +
                                '{/商品}\r\n' +
                                '-付款清单---------------------\r\n' +
                                '{结算}\r\n' +
                                '#pay_name# #pay_money#\r\n' +
                                '{/结算}\r\n' +
                                '-小计-------------------------\r\n' +
                                '数量：$total_num$\r\n' +
                                '金额：$total_money$	实收：$pay_money$\r\n' +
                                '--------------------------------\r\n' +
                                '$brand_name$      $shop_name$\r\n' +
                                '地址：$shop_address$\r\n' +
                                '电话：$shop_tel$\r\n' +
                                '网址：$web_site$\r\n' +
                                '--------------------------------\r\n' +
                                '退换货时凭此票据办理\r\n' +
                                '谢谢惠顾，欢迎再次光临！';
                    
                    }
                    //小票模版内容
                    var str = title + tpl_content;
                    //变量替换 -----------------------------------------------------------
                    record.brand_name = ($rootScope.current_shop.BrandCode == undefined ||  $rootScope.current_shop.BrandCode == '') ?$rootScope.company_info.brand_name:$rootScope.current_shop.BrandCode;
                    record.web_site = $rootScope.company_info.website;
                    str = str.replace(/\$brand_name\$/gm, record.brand_name);
                    str = str.replace(/\$shop_name\$/gm, record.shop_name);
                    str = str.replace(/\$shop_address\$/gm, record.shop_addr);
                    str = str.replace(/\$shop_tel\$/gm, record.shop_tel);
                    str = str.replace(/\$web_site\$/gm, record.web_site);
                    str = str.replace(/\$user_name\$/gm, record.user_name);
                    str = str.replace(/\$guide_name\$/gm, record.guide_user_name);
                    str = str.replace(/\$record_code\$/gm, record.record_code);
                    str = str.replace(/\$record_time\$/gm, record.record_time);
                    str = str.replace(/\$vip_code\$/gm, record.vip_code);
                    str = str.replace(/\$total_num\$/gm, record.total_num);
                    str = str.replace(/\$total_money\$/gm, Number(record.total_money).toFixed(2));
                    str = str.replace(/\$pay_money\$/gm, Number(record.pay_money).toFixed(2));
                    //baison_app.api.alert({msg:str,title:'str1'});
                    //循环替换 商品清单 ----------------------------------------------------
                    str = str.replace(/\{商品\}([\s\S]*?)\{\/商品\}/gm, function (find, goods_tpl) {
                        var goods_str = '';
                        $.each(record['record_detail'], function (i, n) {

                            var goods_li = goods_tpl;
                            //组合sku的规格名称
                            var sku_name = '';
                            var good_name = '';
                            var price = '';
                            var sku_code = '';
                            if (n.color_name != undefined && n.color_name != '') {
                                sku_name = sku_name + n.color_name + ';';
                            }
                            if (n.size_name != undefined && n.size_name != '') {
                                sku_name = sku_name + n.size_name + ';';
                            }
                            if (sku_name == '') {
                                sku_name = n.SkuPropertyName;
                            }
                            if (n.sku != undefined) {
                                sku_code = n.sku;

                            } else if (n.SkuCode != undefined) {
                                sku_code = n.SkuCode;
                            }

                            if (n.goods_name == undefined || n.goods_name == null) {
                                good_name = n.GoodsName;

                            } else {
                                good_name = n.goods_name;

                            }
                            if (n.BuyPrice == undefined || n.BuyPrice == null) {
                                price = n.price;
                            } else {
                                price = n.BuyPrice;
                            }
                            //商品明细替换 ------------------------------------------------
                            goods_li = goods_li.replace(/#num#/gm, n.num);
                            goods_li = goods_li.replace(/#goods_name#/gm, good_name);
                            goods_li = goods_li.replace(/#sku_name#/gm, sku_code);
                            goods_li = goods_li.replace(/#price#/gm, Number(price).toFixed(2));
                            goods_li = goods_li.replace(/#money#/gm, Number(n.money).toFixed(2));
                            goods_li = goods_li.replace(/#unit_name#/gm, n.unit_name);
                            goods_li = goods_li.replace(/#weight#/gm, n.weight);
                            //商品明细替换 end --------------------------------------------
                            goods_str += goods_li;
                        });
                        return goods_str;
                    });
                    //baison_app.api.alert({msg:str,title:'str2'});
                    //循环替换 结算清单 ----------------------------------------------------
                    str = str.replace(/\{结算\}([\s\S]*?)\{\/结算\}/gm, function (find, pay_tpl) {
                        var pay_str = '';
                        $.each(record['payment'], function (i, n) {
                            var pay_li = pay_tpl;
                            var pay_name = '';
                            var pay_money = '';
                            if (n.trade_type_code == undefined || n.trade_type_code == null) {
                                pay_name = n.name ? n.name : '';

                            } else {
								//pay_name = n.name?n.name:n.trade_type_name;
                                switch (n.trade_type_code) {
                                    case '001':
                                        pay_name = $rootScope.language.TIPS_CASHIER_CASH_MONEY;
                                        break;
                                    case '002':
                                        pay_name = $rootScope.language.TIP_RECEIPR_CHECK;
                                        break;
                                    case '003':
                                        pay_name = $rootScope.language.MSG_COUPON;
                                        break;
                                    case '004':
                                        pay_name = $rootScope.language.TIPS_CASHIER_INTEGRAL_DEDUCTION;
                                        break;
                                    case '008':
                                        pay_name = $rootScope.language.TIPS_CASHIER_WECHART_SWEEP;
                                        break;
                                    case '009':
                                        pay_name = $rootScope.language.TIPS_CASHIER_ZHIFUBAO_SWEEP;
                                        break;
                                    case '010':
                                        pay_name = $rootScope.language.TIPS_CASHIER_WECHART_SWIPE;
                                        break;
                                    case '011':
                                        pay_name = $rootScope.language.TIPS_CASHIER_ZHIFUBAO_PAY;
                                        break;
                                    case '012':
                                        pay_name = $rootScope.language.TIPS_CASHIER_DEL_NUM_MONEY;
                                        break;
                                    case '016':
                                        pay_name = $rootScope.language.TIPS_CASHIER_VIP_CARD_MONEY;
                                        break;
									case '024':
										pay_name = '口碑支付';
										break;
									case '025':
										pay_name = '伯侨银行活动';
										break;

                                }

                            }
                            if (n.pay_money == undefined || n.pay_money == null) {
                                pay_money = n.money;
                            } else {
                                pay_money = n.pay_money;
                            }
                            //组合sku的规格名称
                            /*var sku_name = '';
                             if (n.color_name != '') {
                             sku_name = sku_name + n.color_name + ';';
                             }
                             if (n.size_name != '') {
                             sku_name = sku_name + n.size_name + ';';
                             }*/
                            //商品明细替换 ------------------------------------------------
                            //pay_li = pay_li.replace(/#pay_name#/gm, n.trade_type_code);

                            pay_li = pay_li.replace(/#pay_name#/gm, pay_name);
                            pay_li = pay_li.replace(/#pay_money#/gm, Number(pay_money).toFixed(2));
                            //商品明细替换 end --------------------------------------------
                            pay_str += pay_li;
                        });


                        return pay_str;
                    });
                    //baison_app.api.alert({msg:str,title:'str3'});
                    //要打印的字符串信息
                    callback(str);
                };
                var stock_print_tpl_to_string = function (title, tpl_content, record, callback) {
                    //baison_app.api.alert({msg:record,title:'record'});
                    // 没有选择模版时 默认的模版 
                    if (tpl_content == '') {
                        tpl_content ='当前库存\r\n'+
                                '截至日期：$check_time$\r\n' +
								'$brand_name$\r\n'+
                                '柜台：$shop_name$\r\n' +
                                '商品名称数量：$pruductname_num$\r\n' +
                                '-盘点商品清单---------------------\r\n' +
                                '商品条码                数量' +
                                '{商品}\r\n' +
                                '#goods_name#(#unit_name#/#weight#)\r\n'+
								'#sku_code#        #num#\r\n' +
                                '{/商品}\r\n' +
                                '--------------------------------\r\n' +
                                '$brand_name$      $shop_name$\r\n' +
                                '地址：$shop_address$\r\n' +
                                '电话：$shop_tel$\r\n' +
                                '网址：$web_site$\r\n' +
                                '--------------------------------\r\n';
								
                    }
                    var stock_detail_num = record.stock_detail.length;
                    //库存模版内容
                    var str = title + tpl_content;
                    //变量替换 -----------------------------------------------------------
                    record.brand_name = ($rootScope.current_shop.BrandCode == undefined ||  $rootScope.current_shop.BrandCode == '') ?$rootScope.company_info.brand_name:$rootScope.current_shop.BrandCode;
                    record.web_site = $rootScope.company_info.website;
                    str = str.replace(/\$brand_name\$/gm, record.brand_name);
                    str = str.replace(/\$shop_name\$/gm, record.shop_name);
                    str = str.replace(/\$pruductname_num\$/gm, stock_detail_num);

                    str = str.replace(/\$shop_address\$/gm, record.shop_addr);
                    str = str.replace(/\$shop_tel\$/gm, record.shop_tel);
                    str = str.replace(/\$web_site\$/gm, record.web_site);
                    str = str.replace(/\$user_name\$/gm, record.user_name);
                    str = str.replace(/\$check_code\$/gm, record.check_code);
                    str = str.replace(/\$check_time\$/gm, record.check_time);

                    //baison_app.api.alert({msg:str,title:'str1'});
                    //循环替换 商品清单 ----------------------------------------------------
                    str = str.replace(/\{商品\}([\s\S]*?)\{\/商品\}/gm, function (find, goods_tpl) {
                        var goods_str = '';
                        $.each(record['stock_detail'], function (i, n) {

                            var goods_li = goods_tpl;
                            //商品明细替换 ------------------------------------------------
                            goods_li = goods_li.replace(/#num#/gm, n.SkuNum);
                            goods_li = goods_li.replace(/#goods_name#/gm, n.GoodsName);
                            goods_li = goods_li.replace(/#sku_code#/gm, n.SkuCode);
							goods_li = goods_li.replace(/#unit_name#/gm, n.unit_name);
                            goods_li = goods_li.replace(/#weight#/gm, n.weight);
                            //商品明细替换 end --------------------------------------------
                            goods_str += goods_li;
                        });
                        return goods_str;
                    });
                    //要打印的字符串信息
                    callback(str);
                };

                //added by lqx maowei on 20170119 入库申请单详细页面打印模板start
                var peihuo_detail_tpl_to_string = function (title, tpl_content, record, callback) {
                    //baison_app.api.alert({msg:record,title:'record'});
                    // 没有选择模版时 默认的模版 
                    var this_good_name = '';
                    if (tpl_content == '') {
                        tpl_content ='订货申请单\r\n'+
                                '日期：$date$\r\n' +
                                '发货方：$sender$\r\n' +
                                '收货方：$reciever$\r\n' +
                                '单号：$sheetcode$\r\n' +
                                '申请人：$applier$\r\n' +
                                '数量：$num$\r\n' +
                                '状态：$status$\r\n' +
                                '--------------------------------\r\n' +
                                '{商品}\r\n' +
                                '#goods_name#\r\n'+
                                '#sku_code#        #num#\r\n' +
                                '{/商品}\r\n' +
                                '--------------------------------\r\n';                     
                    }
                    //库存模版内容
                    var str = title + tpl_content;
                    var nodata = "暂无数据";
                    var username = $rootScope.user.UserName;
                    var is_check = check_ico_for_print(record.record.is_check);

                   

                    //变量替换 -----------------------------------------------------------
                    str = str.replace(/\$date\$/gm, record.record.record_time);
                    str = str.replace(/\$sender\$/gm, record.record.store_name);
                    str = str.replace(/\$reciever\$/gm, record.record.shop_name);
                    str = str.replace(/\$sheetcode\$/gm, record.record.record_code);
                    str = str.replace(/\$applier\$/gm, username);
                    str = str.replace(/\$num\$/gm, record.record.num);
                    str = str.replace(/\$status\$/gm, is_check);

                    //baison_app.api.alert({msg:str,title:'str1'});
                    //循环替换 商品清单 ----------------------------------------------------
                    str = str.replace(/\{商品\}([\s\S]*?)\{\/商品\}/gm, function (find, goods_tpl) {
                        var goods_str = '';
                        $.each(record['record_detail'], function (i, n) {
                            var goods_li = goods_tpl;
                            var ret = BaseGoods.get_GoodsName_by_sku_sync(n.sku)
                                    this_good_name = ret.GoodsName;                                    
                            
                             //商品明细替换 ------------------------------------------------
                            goods_li = goods_li.replace(/#goods_name#/gm, this_good_name);
                            goods_li = goods_li.replace(/#sku_code#/gm, n.sku);
                            goods_li = goods_li.replace(/#num#/gm, n.num);
                            //商品明细替换 end --------------------------------------------
                            goods_str += goods_li;
                            
                        });
                        return goods_str;
                    });
                    //要打印的字符串信息
                    callback(str);
                };
                //added by lqx maowei on 20170119 入库申请单详细页面打印模板end

                //added by lqx maowei on 20170119 入库详细页面打印模板start
                var ruku_detail_tpl_to_string = function (title, tpl_content, record, callback) {
                    var this_good_name = '';
                    if (tpl_content == '') {
                        tpl_content ='订货入库单\r\n'+
                                '日期：$date$\r\n' +
                                '发货方：$sender$\r\n' +
                                '收货方：$reciever$\r\n' +
                                '单号：$sheetcode$\r\n' +
                                '申请人：$applier$\r\n' +
                                '数量：$num$\r\n' +
                                '状态：$is_sure$ $is_allocate_stock_out$ $is_shop_stock_in$\r\n' +
                                '--------------------------------\r\n' +
                                '{商品}\r\n' +
                                '#goods_name#\r\n'+
                                '#sku_code#        #num#\r\n' +
                                '{/商品}\r\n' +
                                '--------------------------------\r\n';                     
                    }
                    //库存模版内容
                    var str = title + tpl_content;
                    var nodata = "暂无数据";
                    var username = $rootScope.user.UserName;
                    var is_sure = check_is_sure_for_print(record.record.is_sure);
                    var is_allocate_stock_out = check_is_allocate_for_print(record.record.is_allocate_stock_out);
                    var is_shop_stock_in = check_is_stock_in_for_print(record.record.is_shop_stock_in);
 
                    //变量替换 -----------------------------------------------------------
                    str = str.replace(/\$date\$/gm, record.record.record_time);
                    str = str.replace(/\$sender\$/gm, record.record.store_name);
                    str = str.replace(/\$reciever\$/gm, record.record.shop_name);
                    str = str.replace(/\$sheetcode\$/gm, record.record.record_code);
                    str = str.replace(/\$applier\$/gm, username);
                    str = str.replace(/\$num\$/gm, record.record.num);
                    str = str.replace(/\$is_sure\$/gm, is_sure);
                    str = str.replace(/\$is_allocate_stock_out\$/gm, is_allocate_stock_out);
                    str = str.replace(/\$is_shop_stock_in\$/gm, is_shop_stock_in);
                 

                    //baison_app.api.alert({msg:str,title:'str1'});
                    //循环替换 商品清单 ----------------------------------------------------
                    str = str.replace(/\{商品\}([\s\S]*?)\{\/商品\}/gm, function (find, goods_tpl) {
                        var goods_str = '';
                        $.each(record['record_detail'], function (i, n) {
                            var goods_li = goods_tpl;
                            var ret = BaseGoods.get_GoodsName_by_sku_sync(n.sku)
                                    this_good_name = ret.GoodsName;                                    
                            
                             //商品明细替换 ------------------------------------------------
                            goods_li = goods_li.replace(/#goods_name#/gm, this_good_name);
                            goods_li = goods_li.replace(/#sku_code#/gm, n.sku);
                            goods_li = goods_li.replace(/#num#/gm, n.num);
                            //商品明细替换 end --------------------------------------------
                            goods_str += goods_li;
                            
                        });
                        return goods_str;
                    });
                    //要打印的字符串信息
                    callback(str);
                };
                //added by lqx maowei on 20170119 入库详细页面打印模板end

                //added by lqx maowei on 20170119 退库详细页面打印模板start
                var tuiku_detail_tpl_to_string = function (title, tpl_content, record, callback) {
                    var this_good_name = '';
                    if (tpl_content == '') {
                        tpl_content ='退库申请单\r\n'+
                                '日期：$date$\r\n' +
                                '发货方：$sender$\r\n' +
                                '收货方：$reciever$\r\n' +
                                '单号：$sheetcode$\r\n' +
                                '申请人：$applier$\r\n' +
                                '数量：$num$\r\n' +
                                '状态：$is_sure$ $is_shop_stock_out$\r\n' +
                                '--------------------------------\r\n' +
                                '{商品}\r\n' +
                                '#goods_name#\r\n'+
                                '#sku_code#        #num#\r\n' +
                                '{/商品}\r\n' +
                                '--------------------------------\r\n';                     
                    }
                    //库存模版内容
                    var str = title + tpl_content;
                    var nodata = "暂无数据";
                    var username = $rootScope.user.UserName;
                    var is_sure = check_is_sure_for_print(record.record.is_sure);
                    var is_shop_stock_out = check_is_allocate_for_print(record.record.is_shop_stock_out);
                   

                    //变量替换 -----------------------------------------------------------
                    str = str.replace(/\$date\$/gm, record.record.record_time);
                    str = str.replace(/\$sender\$/gm, record.record.shop_name);
                    str = str.replace(/\$reciever\$/gm, record.record.store_name);
                    str = str.replace(/\$sheetcode\$/gm, record.record.record_code);
                    str = str.replace(/\$applier\$/gm, username);
                    str = str.replace(/\$num\$/gm, record.record.num);
                    str = str.replace(/\$is_sure\$/gm, is_sure);
                    str = str.replace(/\$is_shop_stock_out\$/gm, is_shop_stock_out);
                 

                    //baison_app.api.alert({msg:str,title:'str1'});
                    //循环替换 商品清单 ----------------------------------------------------
                    str = str.replace(/\{商品\}([\s\S]*?)\{\/商品\}/gm, function (find, goods_tpl) {
                        var goods_str = '';
                        $.each(record['record_detail'], function (i, n) {
                            var goods_li = goods_tpl;
                            var ret = BaseGoods.get_GoodsName_by_sku_sync(n.sku)
                                    this_good_name = ret.GoodsName;                                    
                            
                             //商品明细替换 ------------------------------------------------
                            goods_li = goods_li.replace(/#goods_name#/gm, this_good_name);
                            goods_li = goods_li.replace(/#sku_code#/gm, n.sku);
                            goods_li = goods_li.replace(/#num#/gm, n.num);
                            //商品明细替换 end --------------------------------------------
                            goods_str += goods_li;
                            
                        });
                        return goods_str;
                    });
                    //要打印的字符串信息
                    callback(str);
                };
                //added by lqx maowei on 20170119 退库详细页面打印模板end

                //added by lqx maowei on 20170209 横调申请详细页面打印模板start
                var hendiaoshenqing_detail_tpl_to_string = function (title, tpl_content, record, callback) {
                    var this_good_name = '';
                    if (tpl_content == '') {
                        tpl_content ='横调申请详细\r\n'+
                                '日期：$date$\r\n' +
                                '移出仓库：$sender$\r\n' +
                                '移入仓库：$reciever$\r\n' +
                                '来源单号：$sheetcode$\r\n' +
                                '申请人：$applier$\r\n' +
                                '数量：$num$\r\n' +
                                '状态：$is_sure$ $is_shop_stock_out$\r\n' +
                                '--------------------------------\r\n' +
                                '{商品}\r\n' +
                                '#goods_name#\r\n'+
                                '#sku_code#        #num#\r\n' +
                                '{/商品}\r\n' +
                                '--------------------------------\r\n';                     
                    }
                    //库存模版内容
                    var str = title + tpl_content;
                    var nodata = "暂无数据";
                    var username = $rootScope.user.UserName;
                    var is_sure = check_is_sure_for_print(record.stm_store_shift_record.is_sure);
                    var is_shift_out = check_is_allocate_for_print(record.stm_store_shift_record.is_shift_out);
                   
                    //变量替换 -----------------------------------------------------------
                    str = str.replace(/\$date\$/gm, record.stm_store_shift_record.record_time);
                    str = str.replace(/\$sender\$/gm, record.stm_store_shift_record.shift_out_shop_name);
                    str = str.replace(/\$reciever\$/gm, record.stm_store_shift_record.shift_in_shop_name);
                    str = str.replace(/\$sheetcode\$/gm, record.stm_store_shift_record.record_code);
                    str = str.replace(/\$applier\$/gm, username);
                    str = str.replace(/\$num\$/gm, record.stm_store_shift_record.num);
                    str = str.replace(/\$is_sure\$/gm, is_sure);
                    str = str.replace(/\$is_shop_stock_out\$/gm, is_shift_out);
                 
                    //baison_app.api.alert({msg:str,title:'str1'});
                    //循环替换 商品清单 ----------------------------------------------------
                    str = str.replace(/\{商品\}([\s\S]*?)\{\/商品\}/gm, function (find, goods_tpl) {
                        var goods_str = '';
                        $.each(record.stm_store_shift_record['stm_store_shift_record_detaill'], function (i, n) {
                            var goods_li = goods_tpl;
                            var ret = BaseGoods.get_GoodsName_by_sku_sync(n.sku)
                                    this_good_name = ret.GoodsName;                                    
                            
                             //商品明细替换 ------------------------------------------------
                            goods_li = goods_li.replace(/#goods_name#/gm, this_good_name);
                            goods_li = goods_li.replace(/#sku_code#/gm, n.sku);
                            goods_li = goods_li.replace(/#num#/gm, n.num);
                            //商品明细替换 end --------------------------------------------
                            goods_str += goods_li;
                            
                        });

                        return goods_str;
                    });
                    //要打印的字符串信息
                    callback(str);
                }
                //added by lqx maowei on 20170119 横调申请详细页面打印模板end

                //added by lqx maowei on 20170119 横调出库详细页面打印模板start
                var hendiaochuku_detail_tpl_to_string = function (title, tpl_content, record, callback) {
                    var this_good_name = '';
                    if (tpl_content == '') {
                        tpl_content ='调拨出库单\r\n'+
                                '日期：$date$\r\n' +
                                '移出仓库：$sender$\r\n' +
                                '移入仓库：$reciever$\r\n' +
                                '来源单号：$sheetcode$\r\n' +
                                '申请人：$applier$\r\n' +
                                '数量：$num$\r\n' +
                                '状态：$is_sure$ $is_shop_stock_out$\r\n' +
                                '--------------------------------\r\n' +
                                '{商品}\r\n' +
                                '#goods_name#\r\n'+
                                '#sku_code#        #num#\r\n' +
                                '{/商品}\r\n' +
                                '--------------------------------\r\n';                     
                    }
                    //库存模版内容
                    var str = title + tpl_content;
                    var nodata = "暂无数据";
                    var username = $rootScope.user.UserName;
                    var is_sure = check_is_sure_for_print(record.stm_store_shift_record.is_sure);
                    var is_shift_out = check_is_allocate_for_print(record.stm_store_shift_record.is_shift_out);
                   
                    //变量替换 -----------------------------------------------------------
                    str = str.replace(/\$date\$/gm, record.stm_store_shift_record.record_time);
                    str = str.replace(/\$sender\$/gm, record.stm_store_shift_record.shift_out_shop_name);
                    str = str.replace(/\$reciever\$/gm, record.stm_store_shift_record.shift_in_shop_name);
                    str = str.replace(/\$sheetcode\$/gm, record.stm_store_shift_record.record_code);
                    str = str.replace(/\$applier\$/gm, username);
                    str = str.replace(/\$num\$/gm, record.stm_store_shift_record.num);
                    str = str.replace(/\$is_sure\$/gm, is_sure);
                    str = str.replace(/\$is_shop_stock_out\$/gm, is_shift_out);
                 
                    //baison_app.api.alert({msg:str,title:'str1'});
                    //循环替换 商品清单 ----------------------------------------------------
                    str = str.replace(/\{商品\}([\s\S]*?)\{\/商品\}/gm, function (find, goods_tpl) {
                        var goods_str = '';
                        $.each(record.stm_store_shift_record['stm_store_shift_record_detaill'], function (i, n) {
                            var goods_li = goods_tpl;
                            var ret = BaseGoods.get_GoodsName_by_sku_sync(n.sku)
                                    this_good_name = ret.GoodsName;                                    
                            
                             //商品明细替换 ------------------------------------------------
                            goods_li = goods_li.replace(/#goods_name#/gm, this_good_name);
                            goods_li = goods_li.replace(/#sku_code#/gm, n.sku);
                            goods_li = goods_li.replace(/#num#/gm, n.num);
                            //商品明细替换 end --------------------------------------------
                            goods_str += goods_li;
                            
                        });

                        return goods_str;
                    });
                    //要打印的字符串信息
                    callback(str);
                }
                //added by lqx maowei on 20170119 横调出库详细页面打印模板end
                
                //added by lqx maowei on 20170119 横调入库详细页面打印模板start
                var hendiaoruku_detail_tpl_to_string = function (title, tpl_content, record, callback) {
                    var this_good_name = '';
                    if (tpl_content == '') {
                        tpl_content ='调拨出库单\r\n'+
                                '日期：$date$\r\n' +
                                '移出仓库：$sender$\r\n' +
                                '移入仓库：$reciever$\r\n' +
                                '来源单号：$sheetcode$\r\n' +
                                '申请人：$applier$\r\n' +
                                '数量：$num$\r\n' +
                                '状态：$is_sure$ $is_shop_stock_out$\r\n' +
                                '--------------------------------\r\n' +
                                '{商品}\r\n' +
                                '#goods_name#\r\n'+
                                '#sku_code#        #num#\r\n' +
                                '{/商品}\r\n' +
                                '--------------------------------\r\n';                     
                    }
                    //库存模版内容
                    var str = title + tpl_content;
                    var nodata = "暂无数据";
                    var username = $rootScope.user.UserName;
                    var is_sure = check_is_sure_for_print(record.stm_store_shift_record.is_sure);
                    var is_shift_out = check_is_allocate_for_print(record.stm_store_shift_record.is_shift_out);
                   
                    //变量替换 -----------------------------------------------------------
                    str = str.replace(/\$date\$/gm, record.stm_store_shift_record.record_time);
                    str = str.replace(/\$sender\$/gm, record.stm_store_shift_record.shift_out_shop_name);
                    str = str.replace(/\$reciever\$/gm, record.stm_store_shift_record.shift_in_shop_name);
                    str = str.replace(/\$sheetcode\$/gm, record.stm_store_shift_record.record_code);
                    str = str.replace(/\$applier\$/gm, username);
                    str = str.replace(/\$num\$/gm, record.stm_store_shift_record.num);
                    str = str.replace(/\$is_sure\$/gm, is_sure);
                    str = str.replace(/\$is_shop_stock_out\$/gm, is_shift_out);
                 
                    //baison_app.api.alert({msg:str,title:'str1'});
                    //循环替换 商品清单 ----------------------------------------------------
                    str = str.replace(/\{商品\}([\s\S]*?)\{\/商品\}/gm, function (find, goods_tpl) {
                        var goods_str = '';
                        $.each(record.stm_store_shift_record['stm_store_shift_record_detaill'], function (i, n) {
                            var goods_li = goods_tpl;
                            var ret = BaseGoods.get_GoodsName_by_sku_sync(n.sku)
                                    this_good_name = ret.GoodsName;                                    
                            
                             //商品明细替换 ------------------------------------------------
                            goods_li = goods_li.replace(/#goods_name#/gm, this_good_name);
                            goods_li = goods_li.replace(/#sku_code#/gm, n.sku);
                            goods_li = goods_li.replace(/#num#/gm, n.num);
                            //商品明细替换 end --------------------------------------------
                            goods_str += goods_li;
                            
                        });

                        return goods_str;
                    });
                    //要打印的字符串信息
                    callback(str);
                }
                //added by lqx maowei on 20170119 横调入库详细页面打印模板end
                
                //added by lqx maowei on 20170119 盘点差异详细页面打印模板start
                var pandianchayi_detail_tpl_to_string = function (title, tpl_content, record, callback) {
                    var this_good_name = '';
                    if (tpl_content == '') {
                        tpl_content ='盘点差异单\r\n'+
                                '日期：$date$\r\n' +
                                '店铺：$sender$\r\n' +
                                '来源单号：$sheetcode$\r\n' +
                                '申请人：$applier$\r\n' +
                                '数量：$num$\r\n' +
                                '状态：$is_sure$\r\n' +
                                '--------------------------------\r\n' +
                                '{商品}\r\n' +
                                '#goods_name#\r\n'+
                                '#sku_code#        #num#\r\n' +
                                '{/商品}\r\n' +
                                '--------------------------------\r\n';                     
                    }
                    //库存模版内容
                    var str = title + tpl_content;
                    var nodata = "暂无数据";
                    var username = $rootScope.user.UserName;
                    var is_sure = check_is_sure_for_print(record.record.is_sure);
                   
                    //变量替换 -----------------------------------------------------------
                    str = str.replace(/\$date\$/gm, record.record.record_time);
                    str = str.replace(/\$sender\$/gm, record.record.shop_name);

                    str = str.replace(/\$sheetcode\$/gm, record.record.record_code);
                    str = str.replace(/\$applier\$/gm, username);
                    str = str.replace(/\$num\$/gm, record.record.num);
                    str = str.replace(/\$is_sure\$/gm, is_sure);
                 
                    //baison_app.api.alert({msg:str,title:'str1'});
                    //循环替换 商品清单 ----------------------------------------------------
                    str = str.replace(/\{商品\}([\s\S]*?)\{\/商品\}/gm, function (find, goods_tpl) {
                        var goods_str = '';
                        $.each(record['record_detail'], function (i, n) {
                            var goods_li = goods_tpl;
                            var ret = BaseGoods.get_GoodsName_by_sku_sync(n.sku)
                                    this_good_name = ret.GoodsName;                                    
                            
                             //商品明细替换 ------------------------------------------------
                            goods_li = goods_li.replace(/#goods_name#/gm, this_good_name);
                            goods_li = goods_li.replace(/#sku_code#/gm, n.sku);
                            goods_li = goods_li.replace(/#num#/gm, n.num);
                            //商品明细替换 end --------------------------------------------
                            goods_str += goods_li;
                            
                        });

                        return goods_str;
                    });
                    //要打印的字符串信息
                    callback(str);
                }
                //added by lqx maowei on 20170119 盘点差异详细页面打印模板end

                //库存盘点打印
                var stock_print = function (title, record) {
                    var systype = baison_app.api.systemType;
                    var configData = $api.getStorage('configData');
                    var pay_type = configData.zftd;
                    var printData = configData.printData;

                    if (systype == 'ios') {
                        if (baison_app.boxPay == undefined || baison_app.boxPay == null) {
                            baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT});
                            return;
                        }
                    } else if (systype == 'android') {
                        if ((baison_app.usbPrint == undefined || baison_app.usbPrint == null) && (baison_app.printmodule == undefined || baison_app.printmodule == null)) {
                            baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT});
                            return;
                        } else if (printData != undefined) {
                            var usb = printData['usb'];
                            if (usb == 1) {
                                if (baison_app.usbPrint == undefined || baison_app.usbPrint == null) {
                                    baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT});
                                    return;
                                }
                            } 
							/*
							else {
                                if (baison_app.printmodule != undefined && baison_app.printmodule != null) {
                                    baison_app.printmodule.getDevice({}, function (ret, err) {

                                        if (ret.deviceName == undefined) {
                                            baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT_BLUE});
                                            return;
                                        }
                                    });
                                }
                            }
							*/
                        }
                    }

                    //从配置文件里获取库存模版名称
                    var tpl_name = '';
                    if (printData != undefined) {
                        tpl_name = printData['stockvalue'];
                    }

                    //根据小票模版tpl_name 获取小票内容
                    var tpl_content = '';

                    stock_select_tplcontent(tpl_name).then(function (ret) {

                        if (ret[0] != undefined && ret[0].content != undefined && ret[0].content != null) {
                            tpl_content = ret[0].content;
                        }
                        stock_print_tpl_to_string(title, tpl_content, record, function (data) {
                            //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg:data,title:'GoodsName'});
                            //引用打印模块
                            //判断是否是盒子支付方式
                            //var systype = baison_app.api.systemType;
                            if (systype == 'ios') { //盒子支付 暂时支持ios
                                //var configData = $api.getStorage('configData');
                                //var pay_type = configData.zftd;
                                if (pay_type == 1) { //是盒子支付
                                    if (baison_app.boxPay != undefined && baison_app.boxPay != null) {
                                        baison_app.boxPay.printOrder({orderTitle: record.record_code, shop: record.shop_name, text: data}, function (ret, err) {
                                            //无返回
                                        });
                                    }

                                    return;
                                }
                            }

                            //判断是否是usb接口打印
                            if (systype == 'android') {
                                //var configData = $api.getStorage('configData');
                                //var printData = configData.printData;
                                if (printData != undefined) {
                                    var usb = printData['usb'];
                                    if (usb != undefined && usb != null && usb == 1) {
                                        //进行usb打印
                                        if (baison_app.usbPrint != undefined && baison_app.usbPrint != null) {
                                            var param = {text: data};
                                            baison_app.usbPrint.printText(param, function (ret, err) {
                                                //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg: ret, title: 'usb打印'});
                                            });
                                        }
                                        return;
                                    }
                                }
								var configData = $api.getStorage('configData');
								if(configData.feifan.switch==1){
									//非凡打印
									baison_app.feifanPrint.selectDevice(function(){//开启打印机
										var param = {text: data};
										//开始打印
										baison_app.feifanPrint.printText(param, function (ret, err) {
											//baison_app.api.alert({msg: ret, title: '飞凡打印'});
											if(ret.messagePrint==1){//打印成功后切纸
												//切纸
												baison_app.feifanPrint.cutePaper(function(ret,err){
													//baison_app.api.alert({title: "切纸",msg:ret});
													//关闭打印机
													baison_app.feifanPrint.closeDevice(function (ret, err) {
													});
												});
											}

										});
									});
								}
								

                            }
                            var configData = $api.getStorage('configData');
                            var printData = configData.printData;
							var usb = printData['usb'];
							if(configData.feifan.switch!=1 && usb != 1) {
								if (baison_app.printmodule != undefined && baison_app.printmodule != null) {
									baison_app.printmodule.getDevice({}, function (ret, err) {

										if (ret.deviceName == undefined) {
											baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT_BLUE});
											return;
										}
									});
								}
							}

                            //不是盒子支付方式
                            if (baison_app.printmodule != undefined && baison_app.printmodule != null) {
                                baison_app.printmodule.getDevice({}, function (ret, err) {

                                    var param = {text: data};
                                    baison_app.printmodule.printText(param, function (ret, err) {

                                        //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg: ret, title: '打印'});
                                        //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg: err, title: '打印失败'});
                                    });

                                });
                            }
                        });
                    });


                };

                //added by lqx maowei on 20170109 配货单详细打印 start
                var peihuodetail_print = function (title, record) {
                
                    var systype = baison_app.api.systemType;
                    var configData = $api.getStorage('configData');
                    var pay_type = configData.zftd;
                    var printData = configData.printData;

                    if (systype == 'ios') {
                        if (baison_app.boxPay == undefined || baison_app.boxPay == null) {
                            baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT});
                            return;
                        }
                    } else if (systype == 'android') {
                        if ((baison_app.usbPrint == undefined || baison_app.usbPrint == null) && (baison_app.printmodule == undefined || baison_app.printmodule == null)) {
                            baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT});
                            return;
                        } else if (printData != undefined) {
                            var usb = printData['usb'];
                            if (usb == 1) {
                                if (baison_app.usbPrint == undefined || baison_app.usbPrint == null) {
                                    baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT});
                                    return;
                                }
                            } 
                            /*
                            else {
                                if (baison_app.printmodule != undefined && baison_app.printmodule != null) {
                                    baison_app.printmodule.getDevice({}, function (ret, err) {

                                        if (ret.deviceName == undefined) {
                                            baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT_BLUE});
                                            return;
                                        }
                                    });
                                }
                            }
                            */
                        }
                    }

                    //从配置文件里获取库存模版名称
                    /*
                    var tpl_name = '';
                    if (printData != undefined) {
                        tpl_name = printData['stockvalue'];
                    }*/

                    //根据模版tpl_name 获取小票内容
                    var tpl_content = '';

                    //stock_select_tplcontent(tpl_name).then(function (ret) {

                        //if (ret[0] != undefined && ret[0].content != undefined && ret[0].content != null) {
                            //tpl_content = ret[0].content;
                        //}
                        peihuo_detail_tpl_to_string(title, tpl_content, record, function (data) {
                            //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg:data,title:'GoodsName'});
                            //引用打印模块
                            //判断是否是盒子支付方式
                            //var systype = baison_app.api.systemType;
                            if (systype == 'ios') { //盒子支付 暂时支持ios
                                //var configData = $api.getStorage('configData');
                                //var pay_type = configData.zftd;
                                if (pay_type == 1) { //是盒子支付
                                    if (baison_app.boxPay != undefined && baison_app.boxPay != null) {
                                        baison_app.boxPay.printOrder({orderTitle: record.record_code, shop: record.shop_name, text: data}, function (ret, err) {
                                            //无返回
                                        });
                                    }

                                    return;
                                }
                            }

                            //判断是否是usb接口打印
                            if (systype == 'android') {
                                //var configData = $api.getStorage('configData');
                                //var printData = configData.printData;
                                if (printData != undefined) {
                                    var usb = printData['usb'];
                                    if (usb != undefined && usb != null && usb == 1) {
                                        //进行usb打印
                                        if (baison_app.usbPrint != undefined && baison_app.usbPrint != null) {
                                            var param = {text: data};
                                            baison_app.usbPrint.printText(param, function (ret, err) {
                                                //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg: ret, title: 'usb打印'});
                                            });
                                        }
                                        return;
                                    }
                                }
                                var configData = $api.getStorage('configData');
                                if(configData.feifan.switch==1){
                                    //非凡打印
                                    baison_app.feifanPrint.selectDevice(function(){//开启打印机
                                        var param = {text: data};
                                        //开始打印
                                        baison_app.feifanPrint.printText(param, function (ret, err) {
                                            //baison_app.api.alert({msg: ret, title: '飞凡打印'});
                                            if(ret.messagePrint==1){//打印成功后切纸
                                                //切纸
                                                baison_app.feifanPrint.cutePaper(function(ret,err){
                                                    //baison_app.api.alert({title: "切纸",msg:ret});
                                                    //关闭打印机
                                                    baison_app.feifanPrint.closeDevice(function (ret, err) {
                                                    });
                                                });
                                            }

                                        });
                                    });
                                }
                                

                            }
                            var configData = $api.getStorage('configData');
                            var printData = configData.printData;
                            var usb = printData['usb'];
                            if(configData.feifan.switch!=1 && usb != 1) {
                                if (baison_app.printmodule != undefined && baison_app.printmodule != null) {
                                    baison_app.printmodule.getDevice({}, function (ret, err) {

                                        if (ret.deviceName == undefined) {
                                            baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT_BLUE});
                                            return;
                                        }
                                    });
                                }
                            }

                            //不是盒子支付方式
                            if (baison_app.printmodule != undefined && baison_app.printmodule != null) {
                                baison_app.printmodule.getDevice({}, function (ret, err) {

                                    var param = {text: data};
                                    baison_app.printmodule.printText(param, function (ret, err) {

                                        //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg: ret, title: '打印'});
                                        //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg: err, title: '打印失败'});
                                    });

                                });
                            }
                        });
                    //});
                };
                //added by lqx maowei on 20170109 配货单详细打印 end
                
                //added by lqx maowei on 20170109 入库单详细打印 start
                var rukudetail_print = function (title, record) {
                 
                    var systype = baison_app.api.systemType;
                    var configData = $api.getStorage('configData');
                    var pay_type = configData.zftd;
                    var printData = configData.printData;

                    if (systype == 'ios') {
                        if (baison_app.boxPay == undefined || baison_app.boxPay == null) {
                            baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT});
                            return;
                        }
                    } else if (systype == 'android') {
                        if ((baison_app.usbPrint == undefined || baison_app.usbPrint == null) && (baison_app.printmodule == undefined || baison_app.printmodule == null)) {
                            baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT});
                            return;
                        } else if (printData != undefined) {
                            var usb = printData['usb'];
                            if (usb == 1) {
                                if (baison_app.usbPrint == undefined || baison_app.usbPrint == null) {
                                    baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT});
                                    return;
                                }
                            } 
                            /*
                            else {
                                if (baison_app.printmodule != undefined && baison_app.printmodule != null) {
                                    baison_app.printmodule.getDevice({}, function (ret, err) {

                                        if (ret.deviceName == undefined) {
                                            baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT_BLUE});
                                            return;
                                        }
                                    });
                                }
                            }
                            */
                        }
                    }

                    //从配置文件里获取库存模版名称
                    /*
                    var tpl_name = '';
                    if (printData != undefined) {
                        tpl_name = printData['stockvalue'];
                    }*/

                    //根据模版tpl_name 获取小票内容
                    var tpl_content = '';

                    //stock_select_tplcontent(tpl_name).then(function (ret) {

                        //if (ret[0] != undefined && ret[0].content != undefined && ret[0].content != null) {
                            //tpl_content = ret[0].content;
                        //}
                        ruku_detail_tpl_to_string(title, tpl_content, record, function (data) {
                            //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg:data,title:'GoodsName'});
                            //引用打印模块
                            //判断是否是盒子支付方式
                            //var systype = baison_app.api.systemType;
                            if (systype == 'ios') { //盒子支付 暂时支持ios
                                //var configData = $api.getStorage('configData');
                                //var pay_type = configData.zftd;
                                if (pay_type == 1) { //是盒子支付
                                    if (baison_app.boxPay != undefined && baison_app.boxPay != null) {
                                        baison_app.boxPay.printOrder({orderTitle: record.record_code, shop: record.shop_name, text: data}, function (ret, err) {
                                            //无返回
                                        });
                                    }

                                    return;
                                }
                            }

                            //判断是否是usb接口打印
                            if (systype == 'android') {
                                //var configData = $api.getStorage('configData');
                                //var printData = configData.printData;
                                if (printData != undefined) {
                                    var usb = printData['usb'];
                                    if (usb != undefined && usb != null && usb == 1) {
                                        //进行usb打印
                                        if (baison_app.usbPrint != undefined && baison_app.usbPrint != null) {
                                            var param = {text: data};
                                            baison_app.usbPrint.printText(param, function (ret, err) {
                                                //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg: ret, title: 'usb打印'});
                                            });
                                        }
                                        return;
                                    }
                                }
                                var configData = $api.getStorage('configData');
                                if(configData.feifan.switch==1){
                                    //非凡打印
                                    baison_app.feifanPrint.selectDevice(function(){//开启打印机
                                        var param = {text: data};
                                        //开始打印
                                        baison_app.feifanPrint.printText(param, function (ret, err) {
                                            //baison_app.api.alert({msg: ret, title: '飞凡打印'});
                                            if(ret.messagePrint==1){//打印成功后切纸
                                                //切纸
                                                baison_app.feifanPrint.cutePaper(function(ret,err){
                                                    //baison_app.api.alert({title: "切纸",msg:ret});
                                                    //关闭打印机
                                                    baison_app.feifanPrint.closeDevice(function (ret, err) {
                                                    });
                                                });
                                            }

                                        });
                                    });
                                }
                                

                            }
                            var configData = $api.getStorage('configData');
                            var printData = configData.printData;
                            var usb = printData['usb'];
                            if(configData.feifan.switch!=1 && usb != 1) {
                                if (baison_app.printmodule != undefined && baison_app.printmodule != null) {
                                    baison_app.printmodule.getDevice({}, function (ret, err) {

                                        if (ret.deviceName == undefined) {
                                            baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT_BLUE});
                                            return;
                                        }
                                    });
                                }
                            }

                            //不是盒子支付方式
                            if (baison_app.printmodule != undefined && baison_app.printmodule != null) {
                                baison_app.printmodule.getDevice({}, function (ret, err) {

                                    var param = {text: data};
                                    baison_app.printmodule.printText(param, function (ret, err) {

                                        //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg: ret, title: '打印'});
                                        //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg: err, title: '打印失败'});
                                    });

                                });
                            }
                        });
                    //});
                };
                //added by lqx maowei on 20170109 入库单详细打印 end

                //added by lqx maowei on 20170109 退库单详细打印 start
                var tuikudetail_print = function (title, record) {
                 
                    var systype = baison_app.api.systemType;
                    var configData = $api.getStorage('configData');
                    var pay_type = configData.zftd;
                    var printData = configData.printData;

                    if (systype == 'ios') {
                        if (baison_app.boxPay == undefined || baison_app.boxPay == null) {
                            baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT});
                            return;
                        }
                    } else if (systype == 'android') {
                        if ((baison_app.usbPrint == undefined || baison_app.usbPrint == null) && (baison_app.printmodule == undefined || baison_app.printmodule == null)) {
                            baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT});
                            return;
                        } else if (printData != undefined) {
                            var usb = printData['usb'];
                            if (usb == 1) {
                                if (baison_app.usbPrint == undefined || baison_app.usbPrint == null) {
                                    baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT});
                                    return;
                                }
                            } 
                            /*
                            else {
                                if (baison_app.printmodule != undefined && baison_app.printmodule != null) {
                                    baison_app.printmodule.getDevice({}, function (ret, err) {

                                        if (ret.deviceName == undefined) {
                                            baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT_BLUE});
                                            return;
                                        }
                                    });
                                }
                            }
                            */
                        }
                    }

                    //从配置文件里获取库存模版名称
                    /*
                    var tpl_name = '';
                    if (printData != undefined) {
                        tpl_name = printData['stockvalue'];
                    }*/

                    //根据模版tpl_name 获取小票内容
                    var tpl_content = '';

                    //stock_select_tplcontent(tpl_name).then(function (ret) {

                        //if (ret[0] != undefined && ret[0].content != undefined && ret[0].content != null) {
                            //tpl_content = ret[0].content;
                        //}
                        tuiku_detail_tpl_to_string(title, tpl_content, record, function (data) {
                            //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg:data,title:'GoodsName'});
                            //引用打印模块
                            //判断是否是盒子支付方式
                            //var systype = baison_app.api.systemType;
                            if (systype == 'ios') { //盒子支付 暂时支持ios
                                //var configData = $api.getStorage('configData');
                                //var pay_type = configData.zftd;
                                if (pay_type == 1) { //是盒子支付
                                    if (baison_app.boxPay != undefined && baison_app.boxPay != null) {
                                        baison_app.boxPay.printOrder({orderTitle: record.record_code, shop: record.shop_name, text: data}, function (ret, err) {
                                            //无返回
                                        });
                                    }

                                    return;
                                }
                            }

                            //判断是否是usb接口打印
                            if (systype == 'android') {
                                //var configData = $api.getStorage('configData');
                                //var printData = configData.printData;
                                if (printData != undefined) {
                                    var usb = printData['usb'];
                                    if (usb != undefined && usb != null && usb == 1) {
                                        //进行usb打印
                                        if (baison_app.usbPrint != undefined && baison_app.usbPrint != null) {
                                            var param = {text: data};
                                            baison_app.usbPrint.printText(param, function (ret, err) {
                                                //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg: ret, title: 'usb打印'});
                                            });
                                        }
                                        return;
                                    }
                                }
                                var configData = $api.getStorage('configData');
                                if(configData.feifan.switch==1){
                                    //非凡打印
                                    baison_app.feifanPrint.selectDevice(function(){//开启打印机
                                        var param = {text: data};
                                        //开始打印
                                        baison_app.feifanPrint.printText(param, function (ret, err) {
                                            //baison_app.api.alert({msg: ret, title: '飞凡打印'});
                                            if(ret.messagePrint==1){//打印成功后切纸
                                                //切纸
                                                baison_app.feifanPrint.cutePaper(function(ret,err){
                                                    //baison_app.api.alert({title: "切纸",msg:ret});
                                                    //关闭打印机
                                                    baison_app.feifanPrint.closeDevice(function (ret, err) {
                                                    });
                                                });
                                            }

                                        });
                                    });
                                }
                                

                            }
                            var configData = $api.getStorage('configData');
                            var printData = configData.printData;
                            var usb = printData['usb'];
                            if(configData.feifan.switch!=1 && usb != 1) {
                                if (baison_app.printmodule != undefined && baison_app.printmodule != null) {
                                    baison_app.printmodule.getDevice({}, function (ret, err) {

                                        if (ret.deviceName == undefined) {
                                            baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT_BLUE});
                                            return;
                                        }
                                    });
                                }
                            }

                            //不是盒子支付方式
                            if (baison_app.printmodule != undefined && baison_app.printmodule != null) {
                                baison_app.printmodule.getDevice({}, function (ret, err) {

                                    var param = {text: data};
                                    baison_app.printmodule.printText(param, function (ret, err) {

                                        //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg: ret, title: '打印'});
                                        //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg: err, title: '打印失败'});
                                    });

                                });
                            }
                        });
                    //});
                };
                //added by lqx maowei on 20170109 退库单详细打印 end

                //added by lqx maowei on 20170209 横调申请详细打印 start
                var hendiaoshenqingdetail_print = function (title, record){
                    var systype = baison_app.api.systemType;
                    var configData = $api.getStorage('configData');
                    var pay_type = configData.zftd;
                    var printData = configData.printData;

                    if (systype == 'ios') {
                        if (baison_app.boxPay == undefined || baison_app.boxPay == null) {
                            baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT});
                            return;
                        }
                    } else if (systype == 'android') {
                        if ((baison_app.usbPrint == undefined || baison_app.usbPrint == null) && (baison_app.printmodule == undefined || baison_app.printmodule == null)) {
                            baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT});
                            return;
                        } else if (printData != undefined) {
                            var usb = printData['usb'];
                            if (usb == 1) {
                                if (baison_app.usbPrint == undefined || baison_app.usbPrint == null) {
                                    baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT});
                                    return;
                                }
                            } 
                            /*
                            else {
                                if (baison_app.printmodule != undefined && baison_app.printmodule != null) {
                                    baison_app.printmodule.getDevice({}, function (ret, err) {

                                        if (ret.deviceName == undefined) {
                                            baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT_BLUE});
                                            return;
                                        }
                                    });
                                }
                            }
                            */
                        }
                    }

                    //从配置文件里获取库存模版名称
                    /*
                    var tpl_name = '';
                    if (printData != undefined) {
                        tpl_name = printData['stockvalue'];
                    }*/

                    //根据模版tpl_name 获取小票内容
                    var tpl_content = '';

                    //stock_select_tplcontent(tpl_name).then(function (ret) {

                        //if (ret[0] != undefined && ret[0].content != undefined && ret[0].content != null) {
                            //tpl_content = ret[0].content;
                        //}
                        hendiaoshenqing_detail_tpl_to_string(title, tpl_content, record, function (data) {
                            //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg:data,title:'GoodsName'});
                            //引用打印模块
                            //判断是否是盒子支付方式
                            //var systype = baison_app.api.systemType;
                            if (systype == 'ios') { //盒子支付 暂时支持ios
                                //var configData = $api.getStorage('configData');
                                //var pay_type = configData.zftd;
                                if (pay_type == 1) { //是盒子支付
                                    if (baison_app.boxPay != undefined && baison_app.boxPay != null) {
                                        baison_app.boxPay.printOrder({orderTitle: record.record_code, shop: record.shop_name, text: data}, function (ret, err) {
                                            //无返回
                                        });
                                    }

                                    return;
                                }
                            }

                            //判断是否是usb接口打印
                            if (systype == 'android') {
                                //var configData = $api.getStorage('configData');
                                //var printData = configData.printData;
                                if (printData != undefined) {
                                    var usb = printData['usb'];
                                    if (usb != undefined && usb != null && usb == 1) {
                                        //进行usb打印
                                        if (baison_app.usbPrint != undefined && baison_app.usbPrint != null) {
                                            var param = {text: data};
                                            baison_app.usbPrint.printText(param, function (ret, err) {
                                                //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg: ret, title: 'usb打印'});
                                            });
                                        }
                                        return;
                                    }
                                }
                                var configData = $api.getStorage('configData');
                                if(configData.feifan.switch==1){
                                    //非凡打印
                                    baison_app.feifanPrint.selectDevice(function(){//开启打印机
                                        var param = {text: data};
                                        //开始打印
                                        baison_app.feifanPrint.printText(param, function (ret, err) {
                                            //baison_app.api.alert({msg: ret, title: '飞凡打印'});
                                            if(ret.messagePrint==1){//打印成功后切纸
                                                //切纸
                                                baison_app.feifanPrint.cutePaper(function(ret,err){
                                                    //baison_app.api.alert({title: "切纸",msg:ret});
                                                    //关闭打印机
                                                    baison_app.feifanPrint.closeDevice(function (ret, err) {
                                                    });
                                                });
                                            }

                                        });
                                    });
                                }
                                

                            }
                            var configData = $api.getStorage('configData');
                            var printData = configData.printData;
                            var usb = printData['usb'];
                            if(configData.feifan.switch!=1 && usb != 1) {
                                if (baison_app.printmodule != undefined && baison_app.printmodule != null) {
                                    baison_app.printmodule.getDevice({}, function (ret, err) {

                                        if (ret.deviceName == undefined) {
                                            baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT_BLUE});
                                            return;
                                        }
                                    });
                                }
                            }

                            //不是盒子支付方式
                            if (baison_app.printmodule != undefined && baison_app.printmodule != null) {
                                baison_app.printmodule.getDevice({}, function (ret, err) {

                                    var param = {text: data};
                                    baison_app.printmodule.printText(param, function (ret, err) {

                                        //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg: ret, title: '打印'});
                                        //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg: err, title: '打印失败'});
                                    });

                                });
                            }
                        });
                    //});
                }
                //added by lqx maowei on 20170209 横调申请详细打印 end

                //added by lqx maowei on 20170109 横调出库单详细打印 start
                var hendiaochukudetail_print = function (title, record) {
         
                    var systype = baison_app.api.systemType;
                    var configData = $api.getStorage('configData');
                    var pay_type = configData.zftd;
                    var printData = configData.printData;

                    if (systype == 'ios') {
                        if (baison_app.boxPay == undefined || baison_app.boxPay == null) {
                            baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT});
                            return;
                        }
                    } else if (systype == 'android') {
                        if ((baison_app.usbPrint == undefined || baison_app.usbPrint == null) && (baison_app.printmodule == undefined || baison_app.printmodule == null)) {
                            baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT});
                            return;
                        } else if (printData != undefined) {
                            var usb = printData['usb'];
                            if (usb == 1) {
                                if (baison_app.usbPrint == undefined || baison_app.usbPrint == null) {
                                    baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT});
                                    return;
                                }
                            } 
                            /*
                            else {
                                if (baison_app.printmodule != undefined && baison_app.printmodule != null) {
                                    baison_app.printmodule.getDevice({}, function (ret, err) {

                                        if (ret.deviceName == undefined) {
                                            baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT_BLUE});
                                            return;
                                        }
                                    });
                                }
                            }
                            */
                        }
                    }

                    //从配置文件里获取库存模版名称
                    /*
                    var tpl_name = '';
                    if (printData != undefined) {
                        tpl_name = printData['stockvalue'];
                    }*/

                    //根据模版tpl_name 获取小票内容
                    var tpl_content = '';

                    //stock_select_tplcontent(tpl_name).then(function (ret) {

                        //if (ret[0] != undefined && ret[0].content != undefined && ret[0].content != null) {
                            //tpl_content = ret[0].content;
                        //}
                        hendiaochuku_detail_tpl_to_string(title, tpl_content, record, function (data) {
                            //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg:data,title:'GoodsName'});
                            //引用打印模块
                            //判断是否是盒子支付方式
                            //var systype = baison_app.api.systemType;
                            if (systype == 'ios') { //盒子支付 暂时支持ios
                                //var configData = $api.getStorage('configData');
                                //var pay_type = configData.zftd;
                                if (pay_type == 1) { //是盒子支付
                                    if (baison_app.boxPay != undefined && baison_app.boxPay != null) {
                                        baison_app.boxPay.printOrder({orderTitle: record.record_code, shop: record.shop_name, text: data}, function (ret, err) {
                                            //无返回
                                        });
                                    }

                                    return;
                                }
                            }

                            //判断是否是usb接口打印
                            if (systype == 'android') {
                                //var configData = $api.getStorage('configData');
                                //var printData = configData.printData;
                                if (printData != undefined) {
                                    var usb = printData['usb'];
                                    if (usb != undefined && usb != null && usb == 1) {
                                        //进行usb打印
                                        if (baison_app.usbPrint != undefined && baison_app.usbPrint != null) {
                                            var param = {text: data};
                                            baison_app.usbPrint.printText(param, function (ret, err) {
                                                //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg: ret, title: 'usb打印'});
                                            });
                                        }
                                        return;
                                    }
                                }
                                var configData = $api.getStorage('configData');
                                if(configData.feifan.switch==1){
                                    //非凡打印
                                    baison_app.feifanPrint.selectDevice(function(){//开启打印机
                                        var param = {text: data};
                                        //开始打印
                                        baison_app.feifanPrint.printText(param, function (ret, err) {
                                            //baison_app.api.alert({msg: ret, title: '飞凡打印'});
                                            if(ret.messagePrint==1){//打印成功后切纸
                                                //切纸
                                                baison_app.feifanPrint.cutePaper(function(ret,err){
                                                    //baison_app.api.alert({title: "切纸",msg:ret});
                                                    //关闭打印机
                                                    baison_app.feifanPrint.closeDevice(function (ret, err) {
                                                    });
                                                });
                                            }

                                        });
                                    });
                                }
                                

                            }
                            var configData = $api.getStorage('configData');
                            var printData = configData.printData;
                            var usb = printData['usb'];
                            if(configData.feifan.switch!=1 && usb != 1) {
                                if (baison_app.printmodule != undefined && baison_app.printmodule != null) {
                                    baison_app.printmodule.getDevice({}, function (ret, err) {

                                        if (ret.deviceName == undefined) {
                                            baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT_BLUE});
                                            return;
                                        }
                                    });
                                }
                            }

                            //不是盒子支付方式
                            if (baison_app.printmodule != undefined && baison_app.printmodule != null) {
                                baison_app.printmodule.getDevice({}, function (ret, err) {

                                    var param = {text: data};
                                    baison_app.printmodule.printText(param, function (ret, err) {

                                        //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg: ret, title: '打印'});
                                        //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg: err, title: '打印失败'});
                                    });

                                });
                            }
                        });
                    //});
                };
                //added by lqx maowei on 20170109 横调出库单详细打印 end
                
                //added by lqx maowei on 20170109 横调出库单详细打印 start
                var hendiaorukudetail_print = function (title, record) {
                
                    var systype = baison_app.api.systemType;
                    var configData = $api.getStorage('configData');
                    var pay_type = configData.zftd;
                    var printData = configData.printData;

                    if (systype == 'ios') {
                        if (baison_app.boxPay == undefined || baison_app.boxPay == null) {
                            baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT});
                            return;
                        }
                    } else if (systype == 'android') {
                        if ((baison_app.usbPrint == undefined || baison_app.usbPrint == null) && (baison_app.printmodule == undefined || baison_app.printmodule == null)) {
                            baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT});
                            return;
                        } else if (printData != undefined) {
                            var usb = printData['usb'];
                            if (usb == 1) {
                                if (baison_app.usbPrint == undefined || baison_app.usbPrint == null) {
                                    baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT});
                                    return;
                                }
                            } 
                            /*
                            else {
                                if (baison_app.printmodule != undefined && baison_app.printmodule != null) {
                                    baison_app.printmodule.getDevice({}, function (ret, err) {

                                        if (ret.deviceName == undefined) {
                                            baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT_BLUE});
                                            return;
                                        }
                                    });
                                }
                            }
                            */
                        }
                    }

                    //从配置文件里获取库存模版名称
                    /*
                    var tpl_name = '';
                    if (printData != undefined) {
                        tpl_name = printData['stockvalue'];
                    }*/

                    //根据模版tpl_name 获取小票内容
                    var tpl_content = '';

                    //stock_select_tplcontent(tpl_name).then(function (ret) {

                        //if (ret[0] != undefined && ret[0].content != undefined && ret[0].content != null) {
                            //tpl_content = ret[0].content;
                        //}
                        hendiaoruku_detail_tpl_to_string(title, tpl_content, record, function (data) {
                            //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg:data,title:'GoodsName'});
                            //引用打印模块
                            //判断是否是盒子支付方式
                            //var systype = baison_app.api.systemType;
                            if (systype == 'ios') { //盒子支付 暂时支持ios
                                //var configData = $api.getStorage('configData');
                                //var pay_type = configData.zftd;
                                if (pay_type == 1) { //是盒子支付
                                    if (baison_app.boxPay != undefined && baison_app.boxPay != null) {
                                        baison_app.boxPay.printOrder({orderTitle: record.record_code, shop: record.shop_name, text: data}, function (ret, err) {
                                            //无返回
                                        });
                                    }

                                    return;
                                }
                            }

                            //判断是否是usb接口打印
                            if (systype == 'android') {
                                //var configData = $api.getStorage('configData');
                                //var printData = configData.printData;
                                if (printData != undefined) {
                                    var usb = printData['usb'];
                                    if (usb != undefined && usb != null && usb == 1) {
                                        //进行usb打印
                                        if (baison_app.usbPrint != undefined && baison_app.usbPrint != null) {
                                            var param = {text: data};
                                            baison_app.usbPrint.printText(param, function (ret, err) {
                                                //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg: ret, title: 'usb打印'});
                                            });
                                        }
                                        return;
                                    }
                                }
                                var configData = $api.getStorage('configData');
                                if(configData.feifan.switch==1){
                                    //非凡打印
                                    baison_app.feifanPrint.selectDevice(function(){//开启打印机
                                        var param = {text: data};
                                        //开始打印
                                        baison_app.feifanPrint.printText(param, function (ret, err) {
                                            //baison_app.api.alert({msg: ret, title: '飞凡打印'});
                                            if(ret.messagePrint==1){//打印成功后切纸
                                                //切纸
                                                baison_app.feifanPrint.cutePaper(function(ret,err){
                                                    //baison_app.api.alert({title: "切纸",msg:ret});
                                                    //关闭打印机
                                                    baison_app.feifanPrint.closeDevice(function (ret, err) {
                                                    });
                                                });
                                            }

                                        });
                                    });
                                }
                                

                            }
                            var configData = $api.getStorage('configData');
                            var printData = configData.printData;
                            var usb = printData['usb'];
                            if(configData.feifan.switch!=1 && usb != 1) {
                                if (baison_app.printmodule != undefined && baison_app.printmodule != null) {
                                    baison_app.printmodule.getDevice({}, function (ret, err) {

                                        if (ret.deviceName == undefined) {
                                            baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT_BLUE});
                                            return;
                                        }
                                    });
                                }
                            }

                            //不是盒子支付方式
                            if (baison_app.printmodule != undefined && baison_app.printmodule != null) {
                                baison_app.printmodule.getDevice({}, function (ret, err) {

                                    var param = {text: data};
                                    baison_app.printmodule.printText(param, function (ret, err) {

                                        //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg: ret, title: '打印'});
                                        //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg: err, title: '打印失败'});
                                    });

                                });
                            }
                        });
                    //});
                };
                //added by lqx maowei on 20170109 横调出库单详细打印 end

                var pandianchayidetail_print = function (title, record) {
          
                    var systype = baison_app.api.systemType;
                    var configData = $api.getStorage('configData');
                    var pay_type = configData.zftd;
                    var printData = configData.printData;

                    if (systype == 'ios') {
                        if (baison_app.boxPay == undefined || baison_app.boxPay == null) {
                            baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT});
                            return;
                        }
                    } else if (systype == 'android') {
                        if ((baison_app.usbPrint == undefined || baison_app.usbPrint == null) && (baison_app.printmodule == undefined || baison_app.printmodule == null)) {
                            baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT});
                            return;
                        } else if (printData != undefined) {
                            var usb = printData['usb'];
                            if (usb == 1) {
                                if (baison_app.usbPrint == undefined || baison_app.usbPrint == null) {
                                    baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT});
                                    return;
                                }
                            } 
                            /*
                            else {
                                if (baison_app.printmodule != undefined && baison_app.printmodule != null) {
                                    baison_app.printmodule.getDevice({}, function (ret, err) {

                                        if (ret.deviceName == undefined) {
                                            baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT_BLUE});
                                            return;
                                        }
                                    });
                                }
                            }
                            */
                        }
                    }

                    //从配置文件里获取库存模版名称
                    /*
                    var tpl_name = '';
                    if (printData != undefined) {
                        tpl_name = printData['stockvalue'];
                    }*/

                    //根据模版tpl_name 获取小票内容
                    var tpl_content = '';

                    //stock_select_tplcontent(tpl_name).then(function (ret) {

                        //if (ret[0] != undefined && ret[0].content != undefined && ret[0].content != null) {
                            //tpl_content = ret[0].content;
                        //}
                        pandianchayi_detail_tpl_to_string(title, tpl_content, record, function (data) {
                            //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg:data,title:'GoodsName'});
                            //引用打印模块
                            //判断是否是盒子支付方式
                            //var systype = baison_app.api.systemType;
                            if (systype == 'ios') { //盒子支付 暂时支持ios
                                //var configData = $api.getStorage('configData');
                                //var pay_type = configData.zftd;
                                if (pay_type == 1) { //是盒子支付
                                    if (baison_app.boxPay != undefined && baison_app.boxPay != null) {
                                        baison_app.boxPay.printOrder({orderTitle: record.record_code, shop: record.shop_name, text: data}, function (ret, err) {
                                            //无返回
                                        });
                                    }

                                    return;
                                }
                            }

                            //判断是否是usb接口打印
                            if (systype == 'android') {
                                //var configData = $api.getStorage('configData');
                                //var printData = configData.printData;
                                if (printData != undefined) {
                                    var usb = printData['usb'];
                                    if (usb != undefined && usb != null && usb == 1) {
                                        //进行usb打印
                                        if (baison_app.usbPrint != undefined && baison_app.usbPrint != null) {
                                            var param = {text: data};
                                            baison_app.usbPrint.printText(param, function (ret, err) {
                                                //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg: ret, title: 'usb打印'});
                                            });
                                        }
                                        return;
                                    }
                                }
                                var configData = $api.getStorage('configData');
                                if(configData.feifan.switch==1){
                                    //非凡打印
                                    baison_app.feifanPrint.selectDevice(function(){//开启打印机
                                        var param = {text: data};
                                        //开始打印
                                        baison_app.feifanPrint.printText(param, function (ret, err) {
                                            //baison_app.api.alert({msg: ret, title: '飞凡打印'});
                                            if(ret.messagePrint==1){//打印成功后切纸
                                                //切纸
                                                baison_app.feifanPrint.cutePaper(function(ret,err){
                                                    //baison_app.api.alert({title: "切纸",msg:ret});
                                                    //关闭打印机
                                                    baison_app.feifanPrint.closeDevice(function (ret, err) {
                                                    });
                                                });
                                            }

                                        });
                                    });
                                }
                                

                            }
                            var configData = $api.getStorage('configData');
                            var printData = configData.printData;
                            var usb = printData['usb'];
                            if(configData.feifan.switch!=1 && usb != 1) {
                                if (baison_app.printmodule != undefined && baison_app.printmodule != null) {
                                    baison_app.printmodule.getDevice({}, function (ret, err) {
                                        if (ret.deviceName == undefined) {
                                            baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON], title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIP_RECEIPR_EQUIPMENT_PRINT_BLUE});
                                            return;
                                        }
                                    });
                                }
                            }

                            //不是盒子支付方式
                            if (baison_app.printmodule != undefined && baison_app.printmodule != null) {
                                baison_app.printmodule.getDevice({}, function (ret, err) {

                                    var param = {text: data};
                                    baison_app.printmodule.printText(param, function (ret, err) {

                                        //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg: ret, title: '打印'});
                                        //baison_app.api.alert({title: $rootScope.language.COMMON_TITLE_HINT,msg: err, title: '打印失败'});
                                    });

                                });
                            }
                        });
                    //});
                };
                //added by lqx maowei on 20170109 横调出库单详细打印 end

                return {
                    xp_print: xp_print,
                    stock_print: stock_print,
                    peihuodetail_print: peihuodetail_print,
                    rukudetail_print: rukudetail_print,
                    tuikudetail_print: tuikudetail_print,

                    hendiaoshenqingdetail_print: hendiaoshenqingdetail_print,
                    hendiaochukudetail_print: hendiaochukudetail_print,
                    hendiaorukudetail_print: hendiaorukudetail_print,
                    pandianchayidetail_print: pandianchayidetail_print,

                    xp_select_tplname: xp_select_tplname,
                    stock_select_tplname: stock_select_tplname,
                    bluetooth: bluetooth,

                    check_ico_for_print: check_ico_for_print,
                    check_is_sure_for_print: check_is_sure_for_print,
                    check_is_allocate_for_print: check_is_allocate_for_print,
                    check_is_stock_in_for_print: check_is_stock_in_for_print,
                    
                    xp_select_tplcontent: xp_select_tplcontent,
                    xp_print_tpl_to_string: xp_print_tpl_to_string,
                    peihuo_detail_tpl_to_string: peihuo_detail_tpl_to_string,
                    ruku_detail_tpl_to_string: ruku_detail_tpl_to_string,
                    tuiku_detail_tpl_to_string: tuiku_detail_tpl_to_string,

                    hendiaoshenqing_detail_tpl_to_string: hendiaoshenqing_detail_tpl_to_string,
                    hendiaochuku_detail_tpl_to_string: hendiaochuku_detail_tpl_to_string,
                    hendiaoruku_detail_tpl_to_string: hendiaoruku_detail_tpl_to_string,
                    pandianchayi_detail_tpl_to_string: pandianchayi_detail_tpl_to_string
                };
            }])


        //服务单
        .factory('ServiceOrder', ['$rootScope', '$q', 'apiService', 'timeStamp2String', function ($rootScope, $q, apiService, timeStamp2String) {
                //获取获取服务器订金单据
                var get_depositRecord = function (filter) {
                    return apiService('pos/pos/get_depositRecord', filter);
                };
                //定金收银之后更新顾客定金单
                var update_depositRecord = function (filter) {
                    return apiService('pos/pos/update_depositRecord', filter);
                };
                //根据条件进行查询
                var search_depositRecord_by_cond = function (filter) {
                    var param = {};
                    param = filter;
                    param.shop_code = $rootScope.current_shop.ShopCode;
                    return apiService('pos/pos/get_depositRecord_by_cond', param);
                };
                //根据单号获取单据详细信息
                var get_record_detail_by_record_code = function (filter) {
                    return apiService('pos/pos/get_depositRecordDetail', filter);
                };
                //新增订金退款单
                var add_depositReturnRecord = function (filter) {
                    return apiService('pos/pos/add_depositReturnRecord', filter);
                };
                //获取订金退款单
                var get_depositReturnRecord = function (filter) {
                    return apiService('pos/pos/get_depositReturnRecord', filter);
                };
                //根据条件查询订金退款单
                var search_depositReturnRecord_by_cond = function (filter) {
                    var param = {};
                    param = filter;
                    param.shop_code = $rootScope.current_shop.ShopCode;
                    return apiService('pos/pos/get_depositReturnRecord_by_cond', param);
                };
                //获取订金退款单详细信息
                var get_returnRecord_detail_by_record_code = function (filter) {
                    return apiService('pos/pos/get_depositReturnRecordDetail', filter);
                };


                //获取维修单
                var get_fixRecord = function (filter) {
                    var params = {
                        shop_code: $rootScope.current_shop.ShopCode,
                        date: timeStamp2String(filter.date, 'date'),
                        is_pre: filter.is_pre
                    };
                    return apiService('pos/service/get_fixRecord', params);
                };
                //根据单号获取维修单详情
                var get_fixDetail = function (record_code) {
                    return apiService('pos/service/get_fixDetail', {record_code: record_code});
                };
                //根据单号更新维修单
                var update_fixRecord = function (data) {
                    return apiService('pos/service/update_fixRecord', data);
                };
                //新增维修单
                var add_fixRecord = function (data) {
                    data.record.date = timeStamp2String(data.record.date, 'date');
                    data.record.make_date = timeStamp2String(data.record.make_date, 'date');
                    data.record.receive_date = timeStamp2String(data.record.receive_date, 'date');
                    return apiService('pos/service/add_fixRecord', data);
                };
                var search_fixRecord = function (filter) {
                    var params = {
                        shop_code: $rootScope.current_shop.ShopCode,
                        record_time_start: timeStamp2String(filter.record_time_start, 'date'),
                        record_time_end: timeStamp2String(filter.record_time_end, 'date'),
                        record_code: filter.record_code,
                        tel: filter.tel,
                        dianyuan: filter.dianyuan
                    };
                    return apiService('pos/service/search_fixRecord', params);
                };
                return {
                    get_depositRecord: get_depositRecord,
                    search_depositRecord_by_cond: search_depositRecord_by_cond,
                    get_record_detail_by_record_code: get_record_detail_by_record_code,
                    get_fixRecord: get_fixRecord,
                    get_fixDetail: get_fixDetail,
                    update_fixRecord: update_fixRecord,
                    add_fixRecord: add_fixRecord,
                    search_fixRecord: search_fixRecord,
                    add_depositReturnRecord: add_depositReturnRecord,
                    get_depositReturnRecord: get_depositReturnRecord,
                    search_depositReturnRecord_by_cond: search_depositReturnRecord_by_cond,
                    get_returnRecord_detail_by_record_code: get_returnRecord_detail_by_record_code,
                    update_depositRecord: update_depositRecord
                };
            }])
        ;
